# Initialize the SDK

Before processing payments, the SDK must be authenticated and the merchant's configuration synchronized with the Get Mini gateway. This guide covers the essential initialization steps: setting the environment, validating your license, and performing the merchant login.

## Requirements

Before you begin, ensure you have:

- **Bundle ID registered** with Get Mini for license validation
- **License key** associated with your Bundle ID provided by Get Mini
- **Merchant credentials** (username and password for login)
- **Linker flags** configured: `-ObjC` and `-lsqlite3` in Build Settings
- **SDK installed** with all header files accessible via Bridging Header

<Callout type="note">

Complete [Install the SDK](/en/get-mini/ios-sdk/first-steps/install-the-sdk) and [Configure iOS Permissions](/en/get-mini/ios-sdk/first-steps/configure-ios-permissions) before proceeding.

</Callout>

## Initialization Steps

### Step 1: Set Environment and License

The `CommonUtils` class manages global SDK settings. Initialize these as early as possible, ideally in your AppDelegate's `application(_:didFinishLaunchingWithOptions:)`:

```
// Import via Bridging Header: CommonUtils.h
import UIKit

func application(_ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    // 1. Set execution environment
    // Options: "des" (Development), "int" (Integration),
    //          "ccal" (Certification), "real" (Production)
    CommonUtils.setEntorno("des")

    // 2. Set application license provided by Get Mini
    CommonUtils.setAppLicense("YOUR_LICENSE_KEY_HERE")

    return true
}
```

The environment determines which Get Mini gateway servers process your transactions. The license key validates your Bundle ID to prevent unauthorized use.

| Environment | Use Case |
| :---- | :---- |
| `"des"` | Development and initial testing |
| `"int"` | Integration testing with Get Mini |
| `"ccal"` | Pre-production certification |
| `"real"` | Production (requires Get Mini approval) |

<Callout type="warning">

Never set the environment to `"real"` until your application has been officially certified by Get Mini.

</Callout>

### Step 2: Perform Merchant Login

To process transactions, the SDK needs merchant configuration (FUC, Terminal ID, etc.) from the Get Mini gateway. Obtain this by performing a login using `RedsysConfigurationManager`:

```
// Import via Bridging Header: DatosLoginDTO.h, RedsysConfigurationManager.h
func performMerchantLogin() {
    let credentials = DatosLoginDTO(user: "merchant_username",
                                    andPass: "merchant_password")

    RedsysConfigurationManager.obtenerDatosComercioLogin(credentials) { response, error in
        if let merchantData = response,
           let merchant = merchantData.merchantList?.first as? MerchantDataDTO,
           let terminal = merchant.listaTerm?.first as? TerminalDataDTO {
            print("Login successful: \(merchant.nameComplete ?? "")")
            print("FUC: \(terminal.fuc ?? "")")
            print("Terminal: \(terminal.terminal ?? "")")

            // Store merchantData for payment operations
            self.saveMerchantConfiguration(merchantData)
        } else {
            print("Login failed: \(error?.localizedDescription ?? "Unknown error")")
            self.handleLoginError(error)
        }
    }
}
```

The `DatosLoginResponseDTO` returned on success doesn't expose the FUC, terminal, or merchant name directly. It contains `merchantList`, an array of `MerchantDataDTO` objects — read `nameComplete` or `nameReduced` from there for the merchant name. Each `MerchantDataDTO` has its own `listaTerm` array of `TerminalDataDTO` objects, which hold `fuc`, `terminal`, `currency`, and `services` (a list of permission codes).

Store this configuration securely to use when creating `MerchanDTO` objects for payment operations.

<Callout type="warning">

For implementations where credentials are not required for every session, consult the manual regarding "Login sin credenciales" (Transparent Login) options.

</Callout>

### Step 3: Implement Delegate Protocols

Your view controller must conform to SDK delegate protocols to receive callbacks during initialization and payment processing.

```
// Import via Bridging Header: RedsysPinpadManager.h
class PaymentViewController: UIViewController,
                             RedsysDelegateGeneric,
                             RedsysBTPinpadInitDelegate,
                             RedsysBTPinpadPaymentDelegate {

    var merchantConfig: DatosLoginResponseDTO?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Initialization will happen when starting payment flow
    }

    // MARK: - Initialization Delegate

    func onInitFinished(_ result: Any!, orError error: Error!) {
        if let config = result as? PinpadConfig {
            print("PinPad ready for transactions")
            // Proceed to payment
        } else {
            print("Initialization error: \(error?.localizedDescription ?? "")")
        }
    }

    // MARK: - Payment Delegates

    func onPaymentProcess(_ result: Any!, orError error: Error!) {
        // Called during payment processing for progress updates
        print("Payment in progress...")
    }

    func onPaymentFinished(_ result: RespuestaTransaccionDTO!, orError error: Error!) {
        if let transaction = result, error == nil {
            print("Payment approved: \(transaction.codigoAutorizacion ?? "")")
            // Save transaction, generate receipt
        } else {
            print("Payment failed: \(error?.localizedDescription ?? "")")
            // Handle error, allow retry
        }
    }
}
```

These delegates provide callbacks at different stages:
- `onInitFinished` - PIN pad connection and configuration complete
- `onPaymentProcess` - Progress updates during transaction
- `onPaymentFinished` - Final transaction result

## Best Practices

### Secure Credential Handling

**Never hardcode merchant credentials in source code:**

```
// ❌ BAD: Hardcoded credentials
let credentials = DatosLoginDTO(user: "myuser", andPass: "mypass")

// ✅ GOOD: Retrieved from secure storage or backend
let credentials = DatosLoginDTO(
    user: SecureStorage.shared.merchantUsername,
    andPass: SecureStorage.shared.merchantPassword
)
```

Retrieve credentials from your secure backend API or encrypted local storage at runtime. Never commit credentials to version control.

### Delegate Lifecycle Management

Ensure your delegate object (usually a View Controller) remains in memory for the transaction duration. If the View Controller is deallocated before `onPaymentFinished` is called, you won't receive the transaction result.

For complex applications with multiple payment flows, consider creating a dedicated payment coordinator class that implements the delegate protocols and manages all transaction logic separately from view controllers.

### Environment Configuration

Use build configurations to manage different environments:

```
#if DEBUG
    CommonUtils.setEntorno("des")
#else
    CommonUtils.setEntorno("real")  // Only after certification
#endif
```

## Troubleshooting

**License Validation Fails**

Verify your Bundle ID matches exactly what was registered with Get Mini. Check in Xcode under **General > Identity > Bundle Identifier**.

**Login Returns Error**

Ensure you're using the correct environment (`"des"` for test credentials). Verify credentials are valid for the selected environment.

**Delegates Not Called**

Confirm you've set the delegate before calling payment methods and that the delegate object hasn't been deallocated.

## Next Steps

With the SDK initialized and merchant configuration retrieved, proceed to:

* [Quick Start: Your First Sale](/en/get-mini/ios-sdk/first-steps/ios-sdk-quickstart) - Complete payment flow example
* [Transaction Lifecycle](/en/get-mini/ios-sdk/core-concepts/ios-lifecycle) - Understand the payment process phases
* [Security and Licensing](/en/get-mini/ios-sdk/core-concepts/security-pci) - Learn about SDK security features