Skip to content

3DS transactions

Integrate 3D Secure (3DS) into your checkout.

Overview

By implementing 3DS authentication into your payment flow, you benefit from:

  • Additional security: 3DS adds multiple layers of authentication and risk assessment.
  • Liability shift: Successful 3DS authentication typically shifts fraud liability from merchant to card issuer.
  • Higher success rate: Banks are more likely to approve 3DS-authenticated transactions.

However, the 3DS payment flow is longer than the non-3DS one due to the additional authentication steps. It may also require active customer participation if a challenge is presented.

Payment flow

The 3D Secure flow is made up of nine key steps.

Step 1: Submission

The customer taps the submit button or the payment is triggered programmatically. The submitAsync() method in CardSubmitComponent is invoked and validation occurs inside it. If validation passes, the method continues with the payment processing. If it fails, the method exits early and doesn't proceed with the transaction.

Step 2: Card tokenisation

If it's a new card, the SDK sends the card details to the tokenisation service. If it's a saved card, the SDK retrieves the existing token.

Step 3: Evaluation

The SDK evaluates whether 3DS authentication is required. In this flow, 3DS is required based on factors like transaction amount, risk assessment, or regulatory requirements.

Step 4: Pre-initiation

This is the initial step in the 3DS authentication flow. It establishes the authentication session by sending transaction and card details to the payment processor.

This step has two associated callbacks:

  • onPreInitiateAuthentication: (() async -> PreInitiateIntegratedAuthenticationData?)?

    • Purpose: Returns configuration for the authentication setup.
    • Return: PreInitiateIntegratedAuthenticationData containing provider ID, timeout, and authentication indicators.
    • Return nil: To skip 3DS authentication (e.g., for low-risk transactions).
    • Note: This callback is async as it returns data for the SDK to process.
  • onPostInitiateAuthentication: (AuthenticationResult) -> Void

    • Purpose: Receives the result of the pre-initiation call.
    • Parameter: AuthenticationResult (either success or failure).
    • Contains: Authentication ID, state, SCA mandate status, applicable exemptions.

Step 5: Fingerprinting

During this step, device information and browser characteristics are collected by the SDK. It enables risk assessment based on the user's device profile.

Step 6: Authentication

The 3DS server evaluates the transaction risk and determines the authentication path:

  • Frictionless flow: If the transaction is low-risk, authentication completes automatically without customer interaction.
  • Challenge flow: If additional verification is needed, the customer completes the 3DS authentication challenge (PIN entry, SMS code, biometric verification, etc.)

The authentication step has two associated callbacks:

  • onPreAuthentication: (() async -> InitiateIntegratedAuthenticationData?)?

    • Purpose: Configures the main authentication parameters.
    • Return: InitiateIntegratedAuthenticationData with challenge window size, timeout, merchant details.
    • Return nil: To abort the authentication process.
    • Note: This callback is async as it returns data for the SDK to process.
  • onPostAuthentication: (AuthenticationResult) -> Void

    • Purpose: Receives authentication results.
    • Parameter: AuthenticationResult indicating success/failure status.
    • Contains: Complete authentication results for transaction processing.

Step 7: Authentication result

The SDK receives the 3DS authentication result indicating whether authentication was successful, failed, or requires additional action.

Step 8: Authorisation

This is the final step of the 3DS authentication flow. You receive the transaction data along with the 3DS authentication results and decide whether to proceed. At this point, you can still add additional data or cancel the transaction entirely. The SDK then sends the authorisation request to the payment gateway, including the 3DS authentication data.

The authorisation step has two associated callbacks:

  • onPreAuthorisation: ((PreAuthorizationData?) async -> TransactionInitiationData?)?

    • Purpose: Provides final transaction data, including 3DS authentication results. This is your last chance to modify the transaction before authorisation.
    • Parameter: PreAuthorizationData? (optional) containing token identifiers.
    • Return: TransactionInitiationData with additional transaction parameters.
    • Return nil: To cancel the transaction.
    • Note: This callback is async as it returns data for the SDK to process.
  • onPostAuthorisation: ((BaseSubmitResult) -> Void)?

    • Purpose: Receives the final transaction result from the payment gateway.
    • Parameter: BaseSubmitResult (one of AuthorisedSubmitResult, CapturedSubmitResult, RefusedSubmitResult, FailedSubmitResult).
    • Contains: Final transaction status, provider response, authentication confirmation, transaction reference.
    • Usage: Handle payment success/failure, navigate to appropriate screens, update UI state.
    • Note: This callback is NOT async as it only receives results.

Step 9: Authorisation result

You receive the final authorisation response from the payment gateway. The transaction is either approved or declined and final transaction details are available, along with 3DS authentication confirmation.

Implementation

Before you start

To use 3D Secure in your application, you first need to enable it in the Unity Portal:

  1. In the Unity Portal, go to Merchant setup > Merchant groups.
  2. Select a merchant group.
  3. Click the Services tab.
  4. Click Edit in the Card service row.
  5. Click Configure modules in the top right.
  6. Click the toggle next to ThreeD secure service.

You'll also need to get the following from your payment processor:

  • providerId: Your 3DS provider identifier.
  • Test credentials for the sandbox environment.

Step 1: Configure your SDK

To start, set up your CheckoutConfig to include the onGetShopper callback.

import PXPCheckoutSDK

let sessionData = SessionData(
    sessionId: "your-session-id",
    hmacKey: "your-hmac-key",
    encryptionKey: "your-encryption-key"
)

let transactionData = TransactionData(
    amount: Decimal(string: "99.99")!,
    currency: "USD",
    entryType: .ecom,
    intent: TransactionIntentData(card: .authorisation),
    merchantTransactionId: "order-\(UUID().uuidString)",
    merchantTransactionDate: { Date() }
)

let checkoutConfig = CheckoutConfig(
    environment: .test,
    session: sessionData,
    transactionData: transactionData,
    merchantShopperId: "shopper-123",
    ownerType: "MerchantGroup",
    ownerId: "your-owner-id",
    onGetShopper: { async in
        TransactionShopper(
            id: "shopper-123",
            email: "customer@example.com",
            firstName: "John",
            lastName: "Doe"
        )
    }
)

let pxpCheckout = try PxpCheckout.initialize(config: checkoutConfig)

Step 2: Implement callbacks

Next, implement your chosen callbacks. Note that some are required.

var submitConfig = CardSubmitComponentConfig()

// REQUIRED: Provide 3DS configuration
// Note: This callback is async as it returns data
submitConfig.onPreInitiateAuthentication = { async in
    return PreInitiateIntegratedAuthenticationData(
        providerId: "your_3ds_provider_id",
        requestorAuthenticationIndicator: .paymentTransaction,
        timeout: 120
    )
}

// OPTIONAL: Handle the pre-initiation result
submitConfig.onPostInitiateAuthentication = { result in
    print("3DS pre-initiation completed: \(result)")
    
    // Your backend uses the authentication session to evaluate and update decisions
    // for whether to proceed with authentication
    if let failed = result as? FailedAuthenticationResult {
        print("3DS setup failed: \(failed.errorReason ?? "Unknown error")")
    } else {
        print("3DS setup successful")
        // Backend evaluates pre-initiation result to update authentication decision
    }
}

// REQUIRED: Configure main authentication
// Note: This callback is async as it returns data
submitConfig.onPreAuthentication = { async in
    print("Configuring 3DS authentication")
    
    // Get authentication decision (evaluated after onPostInitiateAuthentication)
    let decision = await getAuthenticationDecision()
    
    if !decision {
        // Not proceeding with authentication
        return nil
    }
    
    return InitiateIntegratedAuthenticationData(
        merchantCountryNumericCode: "840",
        merchantLegalName: "Your Company Ltd",
        challengeWindowSize: .size5,
        requestorChallengeIndicator: .noPreference,
        shopper: ThreeDSShopper(email: "customer@example.com"),
        timeout: 300
    )
}

// OPTIONAL: Handle the authentication result
submitConfig.onPostAuthentication = { authResult in
    print("3DS authentication completed: \(authResult)")
    
    // Backend evaluates authentication result to update authorisation decision
    if authResult is FailedAuthenticationResult {
        print("Authentication failed")
        // Don't proceed to authorisation
    } else {
        print("Authentication successful")
        // Backend can now proceed with authorisation decision
    }
}

// REQUIRED: Final transaction approval
// Note: This callback is async as it returns data, and parameter is optional
submitConfig.onPreAuthorisation = { preAuthData async in
    print("Pre-authorisation data: \(String(describing: preAuthData))")
    
    // You can use gatewayTokenId to retrieve token details and update transaction decision
    if let tokenId = preAuthData?.gatewayTokenId {
        let transactionDecision = await getAuthorisationDecision(tokenId)
        
        if !transactionDecision {
            // Not proceeding
            return nil
        }
    }
    
    // Add risk screening data for fraud detection
    return TransactionInitiationData(
        riskScreeningData: RiskScreeningData(
            performRiskScreening: true,
            excludeDeviceData: false,
            deviceSessionId: generateDeviceSessionId(),
            userIp: "192.168.1.100",
            account: RiskScreeningAccount(
                id: "user_12345678",
                creationDateTime: "2024-01-15T10:30:00.000Z"
            ),
            items: [
                RiskScreeningItem(
                    price: 89.99,
                    quantity: 1,
                    category: "Electronics"
                )
            ],
            fulfillments: [
                RiskScreeningFulfillment(
                    type: .shipped,
                    shipping: RiskScreeningShipping(
                        shippingMethod: .express
                    ),
                    recipientPerson: RiskScreeningRecipientPerson(
                        phoneNumber: "+1234567890",
                        email: "customer@example.com"
                    )
                )
            ]
        )
    )
}

// OPTIONAL: Handle the final result
submitConfig.onPostAuthorisation = { result in
    switch result {
    case let authorised as AuthorisedSubmitResult:
        print("Payment successful with 3DS!")
        print("Transaction ID: \(authorised.fundingData.transactionId)")
        // Navigate to success screen
    case let captured as CapturedSubmitResult:
        print("Payment captured with 3DS!")
        print("Transaction ID: \(captured.fundingData.transactionId)")
    case let refused as RefusedSubmitResult:
        print("Payment refused: \(refused.stateData?.message ?? "Unknown")")
        // Show error message
    case let failed as FailedSubmitResult:
        print("Payment failed: \(failed.errorReason ?? "Unknown error")")
        // Show error message
    default:
        print("Unknown result type")
    }
}

let cardSubmit = try pxpCheckout.create(.cardSubmit, componentConfig: submitConfig) as! CardSubmitComponent

Step 3: Handle common scenarios

Conditional 3DS

Use the following snippet to only trigger 3DS transactions above a certain amount.

class Conditional3DSManager {
    private let transactionAmount: Decimal
    
    init(transactionAmount: Decimal) {
        self.transactionAmount = transactionAmount
    }
    
    func createCardSubmitConfig() -> CardSubmitComponentConfig {
        var config = CardSubmitComponentConfig()
        
        config.onPreInitiateAuthentication = { async in
            if self.transactionAmount > 100.0 {
                return PreInitiateIntegratedAuthenticationData(
                    providerId: "your_provider",
                    requestorAuthenticationIndicator: .paymentTransaction,
                    timeout: 120
                )
            } else {
                // Return nil to skip 3DS for small amounts
                return nil
            }
        }
        
        config.onPreAuthorisation = { _ async in return TransactionInitiationData() }
        config.onPostAuthorisation = { _ in }
        
        return config
    }
}

Different transaction types

Use the following snippet to handle different types of transactions.

enum TransactionType {
    case payment
    case recurring
    case addCard
}

class TransactionType3DSManager {
    
    func get3DSConfig(transactionType: TransactionType) -> PreInitiateIntegratedAuthenticationData {
        let indicator: RequestorAuthenticationIndicatorType
        
        switch transactionType {
        case .payment:
            indicator = .paymentTransaction
        case .recurring:
            indicator = .recurringTransaction
        case .addCard:
            indicator = .addCard
        }
        
        return PreInitiateIntegratedAuthenticationData(
            providerId: "your_provider",
            requestorAuthenticationIndicator: indicator,
            timeout: 120
        )
    }
    
    func createCardSubmitConfig(transactionType: TransactionType) -> CardSubmitComponentConfig {
        var config = CardSubmitComponentConfig()
        
        config.onPreInitiateAuthentication = { async in
            return self.get3DSConfig(transactionType: transactionType)
        }
        
        config.onPreAuthorisation = { _ async in return TransactionInitiationData() }
        config.onPostAuthorisation = { _ in }
        
        return config
    }
}

Step 4: Handle errors

Lastly, make sure to implement proper error handling.

class ThreeDS3DSErrorHandler {
    
    func createCardSubmitConfigWithErrorHandling() -> CardSubmitComponentConfig {
        var config = CardSubmitComponentConfig()
        
        config.onSubmitError = { error in
            print("Payment error: \(error)")
            self.handleSubmitError(error)
        }
        
        config.onPostAuthentication = { authResult in
            // Handle authentication failures
            if let failed = authResult as? FailedAuthenticationResult {
                print("Authentication failed: \(failed.errorReason ?? "Unknown error")")
                self.showError("Card authentication failed")
                return
            }
            print("Authentication successful, proceeding to payment")
        }
        
        config.onPreAuthorisation = { _ async in return TransactionInitiationData() }
        config.onPostAuthorisation = { _ in }
        
        return config
    }
    
    private func handleSubmitError(_ error: BaseSdkException) {
        // Handle specific 3DS errors
        switch error.errorCode {
        case "AUTHENTICATION_FAILED":
            showError("Payment authentication failed. Please try again.")
        case "CHALLENGE_TIMEOUT":
            showError("Authentication timed out. Please try again.")
        case "AUTHENTICATION_REJECTED":
            showError("Payment was rejected by your bank.")
        case "TOKEN_VAULT_EXCEPTION":
            showError("Token vault exception.")
        case "VALIDATION_EXCEPTION":
            showError("Validation failed.")
        case "TRANSACTION_AUTHENTICATION_REJECTED":
            showError("Payment was rejected by your bank.")
        case "PRE_INITIATE_AUTHENTICATION_FAILED":
            showError("Pre-initiate authentication failed.")
        case "TRANSACTION_AUTHENTICATION_REQUIRES_SCA_EXEMPTION":
            showError("Transaction authentication requires SCA exemption.")
        case "TRANSACTION_AUTHENTICATION_INVALID":
            showError("Transaction authentication is invalid.")
        case "NETWORK_SDK_EXCEPTION":
            showError("Network error occurred. Please try again.")
        case "UNEXPECTED_SDK_EXCEPTION":
            showError("Payment failed. Please try again.")
        default:
            showError("Payment failed. Please try again.")
        }
    }
    
    private func showError(_ message: String) {
        // Implementation depends on your UI framework
        print("Error: \(message)")
    }
}

Complete example

The following example shows a simple 3DS implementation using the new card component in a complete SwiftUI view.

import SwiftUI
import PXPCheckoutSDK

struct ThreeDSPaymentView: View {
    @StateObject private var viewModel = ThreeDSPaymentViewModel()
    
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                Text("3DS Secure Payment")
                    .font(.title)
                    .padding(.bottom, 8)
                
                // Show authentication status
                if let state = viewModel.authenticationState {
                    HStack {
                        Image(systemName: "lock.shield")
                        Text("Authentication Status: \(state)")
                    }
                    .padding()
                    .background(Color.blue.opacity(0.1))
                    .cornerRadius(8)
                }
                
                // Show error message if any
                if let error = viewModel.errorMessage {
                    HStack {
                        Image(systemName: "exclamationmark.triangle")
                        Text(error)
                    }
                    .padding()
                    .background(Color.red.opacity(0.1))
                    .foregroundColor(.red)
                    .cornerRadius(8)
                }
                
                // Render payment component
                if let newCard = viewModel.newCardComponent {
                    newCard.buildContent()
                }
                
                // Loading indicator
                if viewModel.isLoading {
                    HStack {
                        Spacer()
                        VStack(spacing: 8) {
                            ProgressView()
                            Text("Processing 3DS Authentication...")
                                .font(.caption)
                        }
                        Spacer()
                    }
                    .padding()
                }
            }
            .padding()
        }
        .onAppear {
            viewModel.setupComponents()
        }
    }
}

class ThreeDSPaymentViewModel: ObservableObject {
    @Published var isLoading = false
    @Published var errorMessage: String?
    @Published var authenticationState: String?
    var newCardComponent: NewCardComponent?
    
    private var pxpCheckout: PxpCheckout?
    private let errorHandler = ThreeDS3DSErrorHandler()
    
    func setupComponents() {
        do {
            // Setup checkout
            let sessionData = SessionData(
                sessionId: "session-\(UUID().uuidString)",
                hmacKey: "your-hmac-key",
                encryptionKey: "your-encryption-key"
            )
            
            let transactionData = TransactionData(
                amount: Decimal(string: "99.99")!,
                currency: "USD",
                entryType: .ecom,
                intent: TransactionIntentData(card: .authorisation),
                merchantTransactionId: "order-\(UUID().uuidString)",
                merchantTransactionDate: { Date() }
            )
            
            let checkoutConfig = CheckoutConfig(
                environment: .test,
                session: sessionData,
                transactionData: transactionData,
                merchantShopperId: "shopper-123",
                ownerType: "MerchantGroup",
                ownerId: "your-owner-id",
                onGetShopper: { async in
                    TransactionShopper(
                        id: "shopper-123",
                        email: "customer@example.com",
                        firstName: "John",
                        lastName: "Doe"
                    )
                }
            )
            
            pxpCheckout = try PxpCheckout.initialize(config: checkoutConfig)
            
            // Setup submit config with 3DS
            var submitConfig = CardSubmitComponentConfig()
            
            // Step 1: Set up 3DS (async callback)
            submitConfig.onPreInitiateAuthentication = { async in
                return PreInitiateIntegratedAuthenticationData(
                    providerId: "your_3ds_provider_id",
                    requestorAuthenticationIndicator: .paymentTransaction,
                    timeout: 120
                )
            }
            
            // Step 2: Configure authentication (async callback)
            submitConfig.onPreAuthentication = { async in
                return InitiateIntegratedAuthenticationData(
                    merchantCountryNumericCode: "840",
                    merchantLegalName: "Your Company Ltd",
                    challengeWindowSize: .size5,
                    requestorChallengeIndicator: .noPreference,
                    timeout: 300
                )
            }
            
            // Step 3: Handle final authorisation (async callback, optional parameter)
            submitConfig.onPreAuthorisation = { preAuthData async in
                print("Pre-authorisation data: \(String(describing: preAuthData))")
                
                // Add risk screening data for fraud detection
                return TransactionInitiationData(
                    riskScreeningData: RiskScreeningData(
                        performRiskScreening: true,
                        excludeDeviceData: false,
                        deviceSessionId: generateDeviceSessionId(),
                        userIp: "192.168.1.100",
                        account: RiskScreeningAccount(
                            id: "user_12345678",
                            creationDateTime: "2024-01-15T10:30:00.000Z"
                        ),
                        items: [
                            RiskScreeningItem(
                                price: 89.99,
                                quantity: 1,
                                category: "Electronics"
                            )
                        ],
                        fulfillments: [
                            RiskScreeningFulfillment(
                                type: .shipped,
                                recipientPerson: RiskScreeningRecipientPerson(
                                    phoneNumber: "+1234567890"
                                )
                            )
                        ]
                    )
                )
            }
            
            // Step 4: Handle success/failure
            submitConfig.onPostAuthorisation = { [weak self] result in
                DispatchQueue.main.async {
                    switch result {
                    case is AuthorisedSubmitResult, is CapturedSubmitResult:
                        self?.navigateToSuccessScreen()
                    case let refused as RefusedSubmitResult:
                        self?.showError("Payment was declined: \(refused.stateData?.message ?? "Unknown")")
                    default:
                        self?.showError("Payment failed")
                    }
                }
            }
            
            // Step 5: Error handling
            submitConfig.onSubmitError = { [weak self] error in
                print("3DS Error: \(error)")
                DispatchQueue.main.async {
                    self?.showError("Payment authentication failed")
                }
            }
            
            submitConfig.onStartSubmit = { [weak self] in
                DispatchQueue.main.async {
                    self?.isLoading = true
                }
            }
            
            // Create new card component
            let newCardConfig = NewCardComponentConfig(submit: submitConfig)
            newCardComponent = try pxpCheckout?.create(.newCard, componentConfig: newCardConfig) as? NewCardComponent
            
        } catch {
            showError("Failed to initialise payment: \(error.localizedDescription)")
        }
    }
    
    private func navigateToSuccessScreen() {
        // Navigate to success screen
        print("Payment successful!")
    }
    
    private func showError(_ message: String) {
        errorMessage = message
        isLoading = false
    }
}

Callback data

This section describes the data received by the different callbacks as part of the 3DS flow.

Note that the onPreInitiateAuthentication callback doesn't receive anything so isn't included. Instead, it returns your 3DS configuration in the PreInitiateIntegratedAuthenticationData object.

onPostInitiateAuthentication

The onPostInitiateAuthentication callback receives only the authentication identifier. Use this ID to retrieve full authentication details from your backend.

Event data

ParameterDescription
stateDataState information including code and message.

Example implementation

submitConfig.onPostInitiateAuthentication = { result in
    print("3DS pre-initiation completed: \(result)")
    
    // Check for failures
    if let failed = result as? FailedAuthenticationResult {
        print("3DS pre-initiation failed: \(failed.errorReason ?? "Unknown error")")
        return
    }
    
    // Success case - pre-initiation completed
    print("3DS pre-initiation successful")
    
    // Access state data if available
    let stateData = result.stateData
    print("State: \(stateData.code) - \(stateData.message)")
}
        
    // Update UI based on state
    switch stateData.code {
    case "PendingClientData":
        print("Waiting for client data collection")
        updateAuthenticationState("Collecting device data...")
    case "AuthenticationSuccessful":
        print("Authentication completed successfully")
        updateAuthenticationState("Authentication successful")
    default:
        updateAuthenticationState(stateData.code)
    }
}

private func updateAuthenticationState(_ state: String) {
    // Update UI with authentication state
    print("Authentication state updated: \(state)")
}

Success

When successful, onPostInitiateAuthentication receives a success result with the following properties:

ParameterDescription
stateThe state of the authentication.

Possible values:
  • AuthenticationSuccessful
  • AuthenticationFailed
  • AuthenticationRejected
  • PendingCustomerChallenge
  • PendingClientData
stateDataAdditional state information including code and message.

Failure

When unsuccessful, onPostInitiateAuthentication receives a FailedAuthenticationResult with error details:

ParameterDescription
errorCodeThe error code.
errorReasonThe reason for the error.
correlationIdThe correlation ID for tracking.

onPreAuthentication

The onPreAuthentication callback doesn't receive parameters. It should return InitiateIntegratedAuthenticationData with authentication configuration.

Here's an example:

submitConfig.onPreAuthentication = { async in
    print("Configuring 3DS authentication")
    
    // Get authentication decision (evaluated after onPostInitiateAuthentication)
    let decision = await getAuthenticationDecision()
    
    if !decision {
        // Not proceeding with authentication
        return nil
    }
    
    return InitiateIntegratedAuthenticationData(
        merchantCountryNumericCode: "840",
        merchantLegalName: "Your Company Ltd",
        challengeWindowSize: .size5,
        requestorChallengeIndicator: .noPreference,
        shopper: ThreeDSShopper(
            email: "customer@example.com",
            mobilePhone: "+1234567890"
        ),
        timeout: 300
    )
}

onPostAuthentication

The onPostAuthentication callback receives the authentication result with state information.

Event data

ParameterDescription
stateThe state of the authentication.

Possible values:
  • AuthenticationSuccessful
  • AuthenticationFailed
  • AuthenticationRejected
  • PendingCustomerChallenge
  • PendingClientData
stateDataAdditional state information including code and message.

Example implementation

submitConfig.onPostAuthentication = { authResult in
    print("Authentication result: \(authResult)")
    
    // Access state data
    let stateData = authResult.stateData
    print("Authentication state: \(stateData.code) - \(stateData.message)")
    
    // Check authentication result type
    if authResult is SuccessAuthenticationResult {
        print("3DS authentication successful")
    } else if let failed = authResult as? FailedAuthenticationResult {
        print("3DS authentication failed: \(failed.errorReason ?? "Unknown error")")
    }
}
            
            print("Authentication result:", fullAuthResult)
            
            // Check transaction status
            switch fullAuthResult.transactionStatus {
            case "Y":
                print("Authentication successful - no challenge needed")
                showMessage("Card verified successfully")
                
            case "C":
                print("Challenge completed - checking result...")
                if fullAuthResult.state == "AuthenticationSuccessful" {
                    print("Challenge completed successfully")
                    showMessage("Verification completed")
                } else {
                    print("Challenge failed")
                    showError("Verification failed. Please try again.")
                    return
                }
                
            case "N":
                print("Authentication failed")
                showError("Card verification failed")
                return
                
            case "R":
                print("Authentication rejected")
                showError("Payment was rejected by your bank")
                return
                
            default:
                print("Unknown authentication status")
            }
            
            // Backend evaluates authentication result to update authorisation decision
            let authorisationDecision = await evaluateAuthenticationAndUpdateAuthorization(fullAuthResult)
            
            print("Proceeding to final authorisation...")
        }
    }
    
    // Backend evaluates authentication result to update authorisation decision
    if authResult is FailedAuthenticationResult {
        print("Authentication failed")
        showError("Card verification failed. Please try a different payment method.")
        // Don't proceed to authorisation - update session accordingly
    } else {
        print("Authentication successful")
        // Backend can now proceed with authorisation decision
    }
}

private func showMessage(_ message: String) {
    print("Message: \(message)")
}

private func showError(_ message: String) {
    print("Error: \(message)")
}

onPreAuthorisation

The onPreAuthorisation callback receives only the gateway token ID. Use this ID to retrieve token details and make authorisation decisions on your backend.

Event data

ParameterDescription
gatewayTokenIdThe token ID from the payment gateway. Use this ID to retrieve full token details from the Unity backend and update transaction decision.

Use the gatewayTokenId with the Get masked card data related to gateway token API to retrieve full token details including card scheme, funding source (credit/debit), masked PAN, and expiry date.

Example implementation

submitConfig.onPreAuthorisation = { preAuthData async in
    print("Final authorisation data: \(String(describing: preAuthData))")
    
    // Access optional token data if available
    if let tokenId = preAuthData?.gatewayTokenId {
        print("Gateway token: \(tokenId)")
        
        // Use gatewayTokenId to retrieve token details and update transaction decision
        let transactionDecision = await getAuthorisationDecision(tokenId)
        
        if !transactionDecision {
            // Not proceeding
            return nil
        }
    }
    
    // Add risk screening data for fraud detection
    return TransactionInitiationData(
        riskScreeningData: RiskScreeningData(
            performRiskScreening: true,
            excludeDeviceData: false,
            deviceSessionId: generateDeviceSessionId(),
            userIp: "192.168.1.100",
            account: RiskScreeningAccount(
                id: "user_12345678",
                creationDateTime: "2024-01-15T10:30:00.000Z"
            ),
            items: [
                RiskScreeningItem(
                    price: 89.99,
                    quantity: 1,
                    category: "Electronics"
                )
            ],
            fulfillments: [
                RiskScreeningFulfillment(
                    type: .shipped,
                    shipping: RiskScreeningShipping(
                        shippingMethod: .express
                    ),
                    recipientPerson: RiskScreeningRecipientPerson(
                        phoneNumber: "+1234567890",
                        email: "customer@example.com"
                    )
                )
            ]
        )
    )
}

private func generateDeviceSessionId() -> String {
    return UUID().uuidString.replacingOccurrences(of: "-", with: "")
}

3DS external data (obtained from external authentication sources) shouldn't be provided via the threeDSecureData return parameter. Instead, provide this data to the backend via the Modify session API.

Use the gatewayTokenId with the Get masked card data related to gateway token API to retrieve full token details including card scheme, funding source (credit/debit), masked PAN, and expiry date.