# Transaction Lifecycle

Processing a card-present transaction with the Get Mini SDK involves coordinated interaction between your iOS app, the Get Mini Gateway, and physical PIN pad hardware. Understanding this lifecycle helps you build robust payment experiences with appropriate user feedback, error handling, and timeout management.

The SDK manages transaction processing through four distinct phases: **Initialization & Authentication**, **Hardware Discovery**, **Transaction Execution**, and **Result Finalization**. Each phase involves specific operations and state transitions communicated through delegate callbacks.

## Transaction Phases

### Phase 1: Initialization & Authentication

Before interacting with hardware, the SDK must establish its identity and the merchant's context.

**Framework Setup**

Your application configures the SDK environment and license using `CommonUtils`:

```
// Set environment: "des" (Development), "int" (Integration),
// "ccal" (Pre-production), "real" (Production)
CommonUtils.setEntorno("des")

// Set App License provided by Get Mini
CommonUtils.setAppLicense("YOUR_LICENSE_KEY")
```

This configuration determines which Get Mini gateway servers process transactions and validates your application's authorization to use the SDK.

**Merchant Login**

The application performs merchant authentication using `RedsysConfigurationManager`:

```
let loginDTO = DatosLoginDTO(user: "username", andPass: "password")

RedsysConfigurationManager.obtenerDatosComercioLogin(loginDTO) { result, error in
    if let merchantData = result {
        // Store FUC, Terminal ID, and other merchant configuration
    }
}
```

The returned `DatosLoginResponseDTO` contains essential merchant data including FUC (Merchant ID) and Terminal ID required for payment processing.

<Callout type="note">

The SDK also supports "Transparent Login" (Login sin credenciales) for pre-configured terminals that don't require UI-based credential entry.

</Callout>

### Phase 2: Hardware Discovery (External Accessory)

Unlike generic Bluetooth devices, the Get Mini SDK communicates with PIN pads through the iOS **External Accessory framework**.

**Protocol Matching**

The SDK only discovers devices that match protocol strings declared in your `Info.plist` under `UISupportedExternalAccessoryProtocols`. For example, `com.datecs.pinpad` for Itos/Castles devices or `com.ingenico.*` for Ingenico readers. Without these declarations, iOS blocks the SDK from detecting the hardware.

**Device Discovery**

The `RedsysPinpadManager` scans for paired External Accessory devices:

```
let pinpadManager = RedsysPinpadManager(bluetoothTech: "GENERAL")
let availableDevices = pinpadManager.bluetoothDevicesList()
```

This returns an array of `EAAccessory` objects representing physical PIN pads currently paired in iOS Settings > Bluetooth and matching the declared protocols.

**Connection & Configuration**

Once a device is selected, the SDK establishes a session and configures it with merchant data:

```
let merchantDTO = MerchanDTO()
merchantDTO.fuc = "999008881"
merchantDTO.terminal = "001"

pinpadManager.connectAndConfigureDevice(selectedDevice,
                                       merchan: merchantDTO,
                                       withDelegate: self)
```

The `onInitFinished` delegate callback confirms successful connection and returns a `PinpadConfig` object required for payment operations.

### Phase 3: Transaction Execution

Once the PIN pad is connected and configured, your application initiates the payment by creating a `PagoDTO` and calling the payment method.

**Payment Configuration**

Create the payment data transfer object with transaction details:

```
let amount: Float = 10.50
let pagoDTO = PagoDTO(
    valor: Int(amount * 100),  // Amount in cents (1050 for €10.50)
    mMoneda: 978,              // ISO 4217 currency code (978 = EUR)
    nFactura: "ORDER001",      // Unique invoice/order number
    email: "",
    tlfCliente: "",
    datosPropietarios: ""
)
```

<Callout type="warning">

Amounts must be passed as integers representing cents (multiply by 100) to ensure precision across different currency scales.

</Callout>

**Card Interaction**

Execute the payment, which triggers the complete transaction flow:

```
pinpadManager.payWithPinpadBluetooth(
    selectedDevice,
    merchan: merchantDTO,
    config: pinpadConfig,
    andPagoDTO: pagoDTO,
    withDelegate: self
)
```

The PIN pad takes control of user interaction:

1. **Prompts** the customer to Insert, Swipe, or Tap their card
2. **Reads** card data via chip, contactless (NFC), or magnetic stripe
3. **PIN Entry**: If required, the customer enters their PIN on the hardware keypad

> **Security Note**: PIN entry occurs entirely within the PIN pad's secure hardware element. The PIN never enters the iOS device's memory or your application.

**Encryption & Gateway**

The PIN pad encrypts card data using hardware-based End-to-End Encryption (E2EE). The SDK transmits this encrypted payload to Get Mini Gateway servers, which decrypt, process, and forward the transaction to the card network and issuing bank for authorization.

### Phase 4: Finalization & Signature

The gateway returns a response delivered through the `RedsysBTPinpadPaymentDelegate`:

```
func onPaymentFinished(_ result: RespuestaTransaccionDTO!, orError error: Error!) {
    if let transaction = result, error == nil {
        let authCode = transaction.codigoAutorizacion
        // Transaction approved
    } else {
        // Transaction failed or declined
    }
}
```

**Standard Authorization**

For approved transactions, the `RespuestaTransaccionDTO` contains an authorization code that confirms successful payment processing. Save this code for refund operations and reconciliation.

**Signature Required**

If the cardholder did not authenticate via PIN, the response indicates signature requirement through the `AutenticadoPorPin` field:

```
if let transaction = result, transaction.AutenticadoPorPin == false {
    // Capture digital signature
    captureSignature()
}
```

This commonly occurs with offline cards or specific international card flows. Your application must capture the customer's digital signature (as an image) and submit it to complete the legal requirements:

```
let signatureDTO = EnvioFirmaDTO(
    withTerminal: terminalDataDTO,  // TerminalDataDTO with FUC and Terminal
    withFirma: signatureImage,      // UIImage of captured signature
    Format: 2,                      // Format: 1=BMP, 2=JPG, 3=TIF, 4=GIF
    andOperacion: operationDTO      // OperacionDTO from transaction
)

RedsysConfigurationManager.envioFirmaDigitalizada(signatureDTO) { result, error in
    // Signature submission complete
}
```

## State Transition Map

The following table illustrates the internal state flow during transaction processing:

| State | Trigger | Action |
| :---- | :---- | :---- |
| **Ready** | `setAppLicense` called | SDK initialized and idle |
| **Login** | `obtenerDatosComercioLogin` called | Authenticating merchant credentials |
| **Discovery** | `bluetoothDevicesList` called | Scanning for paired EAAccessory devices |
| **Connecting** | `connectAndConfigureDevice` called | Establishing session with PIN pad |
| **Interaction** | `payWithPinpadBluetooth` called | User prompted to present card/enter PIN |
| **Authorizing** | Card data captured | Encrypted payload sent to gateway |
| **Signature** | `AutenticadoPorPin == false` | Optional signature capture required |
| **Finished** | Gateway response received | `onPaymentFinished` callback invoked |

## Key Constraints

Understanding lifecycle constraints helps you design reliable payment experiences:

**Synchronous Operation**

Only one payment operation can be active at a time per `RedsysPinpadManager` instance. Attempting to start a new transaction while one is in progress causes SDK state conflicts and potential duplicate submissions. Implement UI blocking (modal indicators) during active transactions to prevent multiple payment attempts.

**Bluetooth Persistence**

If the Bluetooth connection drops during transaction execution, the SDK attempts automatic reconnection. If reconnection fails, an error callback is triggered with a connection timeout code. Monitor the `onPaymentProcess` callback for progress updates and handle connection errors gracefully.

**Amount Formatting**

Amounts must be passed as integers representing cents to ensure precision:

| Amount | Format | PagoDTO Value |
| :---- | :---- | :---- |
| €10.50 | 10.50 * 100 | `1050` |
| €100.00 | 100.00 * 100 | `10000` |
| \$25.99 | 25.99 * 100 | `2599` |

This prevents floating-point precision issues across different currency scales and ensures accurate transaction processing.

**External Accessory Protocols**

The SDK only communicates with devices matching protocols declared in `Info.plist`. Missing protocol declarations prevent device discovery entirely—iOS blocks the SDK from detecting PIN pad hardware without these entries.

## Next Steps

* [Quick Start: Your First Sale](/en/get-mini/ios-sdk/first-steps/ios-sdk-quickstart) - Implement the complete transaction flow step-by-step
* [Configure iOS Permissions](/en/get-mini/ios-sdk/first-steps/configure-ios-permissions) - Set up required External Accessory protocols