### Clone the repository Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/Example/README.md Clone the mobile-payments-sdk-ios repository to get the example app. This is a prerequisite for running the example. ```bash git clone https://github.com/square/mobile-payments-sdk-ios ``` -------------------------------- ### Usage example for startPayment Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Shows how to configure and start a payment with PaymentParameters and PromptParameters. Uses .onlineOnly in Sandbox and .autoDetect in production. The example is from Example/DonutCounter/DonutCounter/Screens/Home/HomeView.swift. ```swift let paymentAttemptID = UUID().uuidString // base on an order/sale ID in production let paymentParameters = PaymentParameters( paymentAttemptID: paymentAttemptID, amountMoney: Money(amount: 100, currency: .USD), processingMode: processingMode() // .onlineOnly in Sandbox, .autoDetect in production ) let promptParameters = PromptParameters(mode: .default, additionalMethods: .all) mobilePaymentsSDK.paymentManager.startPayment( paymentParameters, promptParameters: promptParameters, from: viewHolder.controller, delegate: viewModel ) ``` -------------------------------- ### PairingCoordinator usage example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Example of implementing ReaderPairingDelegate and starting pairing with a coordinator. ```swift final class PairingCoordinator: ReaderPairingDelegate { func readerPairingDidBegin() { print("started") } func readerPairingDidSucceed() { print("paired") } func readerPairingDidFail(with error: any Error) { print("pairing failed: \(error)") } } let handle = mobilePaymentsSDK.readerManager.startPairing(with: coordinator) ``` -------------------------------- ### startPayment(_:promptParameters:from:delegate:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Starts a payment flow with the provided parameters and prompt configuration. Returns a PaymentHandle for cancellation and inspection, or nil if the payment could not be started. ```APIDOC ## [POST] startPayment(_:promptParameters:from:delegate:) ### Description Starts a payment flow with the provided parameters and prompt configuration. Returns a PaymentHandle for cancellation and inspection, or nil if the payment could not be started. ### Method POST ### Endpoint startPayment(_:promptParameters:from:delegate:) ### Parameters #### Request Body - **paymentParameters** (`PaymentParameters`) - Required - Payment, amount, and processing configuration. - **promptParameters** (`PromptParameters`) - Required - Which SDK payment prompt UI to show. - **viewController** (`UIViewController`) - Required - Presenting view controller for the prompt UI. - **delegate** (`any PaymentManagerDelegate`) - Required - Receives lifecycle callbacks for the payment. ### Request Example ```swift let paymentAttemptID = UUID().uuidString // base on an order/sale ID in production let paymentParameters = PaymentParameters( paymentAttemptID: paymentAttemptID, amountMoney: Money(amount: 100, currency: .USD), processingMode: processingMode() // .onlineOnly in Sandbox, .autoDetect in production ) let promptParameters = PromptParameters(mode: .default, additionalMethods: .all) mobilePaymentsSDK.paymentManager.startPayment( paymentParameters, promptParameters: promptParameters, from: viewHolder.controller, delegate: viewModel ) ``` ### Response #### Success Response (200) - **PaymentHandle** (any PaymentHandle?) - Optional handle for cancellation and inspection; nil if the payment could not be started. #### Response Example ```swift let handle = mobilePaymentsSDK.paymentManager.startPayment(...) ``` ### Error Handling Fails (via the delegate's `didFail`) with `PaymentError` cases such as `.paymentAlreadyInProgress`, `.notAuthorized`, `.timedOut`. ### Error Example ```swift func paymentManager(_ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error) { let paymentError = PaymentError(rawValue: (error as NSError).code) switch paymentError { case .paymentAlreadyInProgress, .notAuthorized, .timedOut: print(error) case .idempotencyKeyReused: print("Developer error: idempotency key reused; check recent payments' status.") default: print(error) } } ``` ``` -------------------------------- ### startPairing(with:) method signature Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Starts a pairing flow with the given delegate. Returns an optional PairingHandle to stop pairing, or nil if pairing could not start. ```swift @discardableResult @objc func startPairing(with delegate: any ReaderPairingDelegate) -> (any PairingHandle)? ``` -------------------------------- ### Start a Payment with PaymentParameters and PromptParameters Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/AGENTS.md Start a payment using paymentManager.startPayment. paymentAttemptID must be derived from an order/sale identifier to prevent duplicate payments. Sandbox supports only .onlineOnly processing; use .autoDetect in production. ```swift let paymentParameters = PaymentParameters( paymentAttemptID: paymentAttemptID, amountMoney: Money(amount: 100, currency: .USD), processingMode: .autoDetect ) let promptParameters = PromptParameters(mode: .default, additionalMethods: .all) MobilePaymentsSDK.shared.paymentManager.startPayment( paymentParameters, promptParameters: promptParameters, from: viewController, delegate: self ) ``` -------------------------------- ### Usage example: CardReader observer and read flow Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/read-card-info.md Shows a complete usage example: a CardReader class conforming to ReadCardInfoObserver, then adding it to the manager and calling prepareToReadCardInfoOnce. The comment indicates how to later charge the card via PaymentParameters.cardHandle. ```swift final class CardReader: ReadCardInfoObserver { var cardHandle: (any CardHandle)? func readCardInfoDidSucceed(_ handle: any CardHandle) { cardHandle = handle // later: PaymentParameters(idempotencyKey:…, amountMoney:…, processingMode:…).cardHandle = handle } func readCardInfoDidFail(_ error: ReadCardInfoError) { print("card read failed: \(error)") } } let reader = mobilePaymentsSDK.readCardInfoManager reader.add(cardReader) reader.prepareToReadCardInfoOnce(storeSwipedCard: false, shouldReadPreInsertedCard: true) ``` -------------------------------- ### Usage example: presentSettings(with:completion:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md From Example/DonutCounter/DonutCounter/Screens/Home/HomeView.swift. Calls the settings manager to present the settings screen, printing any error. ```swift mobilePaymentsSDK.settingsManager.presentSettings( with: viewHolder.controller ) { error in if let error { print(error.localizedDescription) } } ``` -------------------------------- ### Usage example: MockMobilePaymentsSDK adopter implementation Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mobile-payments-sdk.md Example from MockMobilePaymentsSDK.swift showing a class conforming to SDKManager. It declares all five sub-manager properties and assigns them in init. ```swift class MockMobilePaymentsSDK: NSObject, SDKManager { let authorizationManager: AuthorizationManager let paymentManager: PaymentManager let readCardInfoManager: ReadCardInfoManager let readerManager: ReaderManager let settingsManager: SettingsManager // ... init assigns all five } ``` -------------------------------- ### Currency usage example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Creates a Money instance with a currency, from HomeView.swift. ```swift let money = Money(amount: 100, currency: .USD) ``` -------------------------------- ### ReaderObserver Implementation Example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Example observer class that implements ReaderObserver methods to handle reader addition, removal, and change events. Register with readerManager.add(_:) on view appear and remove on disappear. ```swift final class ReaderMonitor: ReaderObserver { func readerWasAdded(_ readerInfo: any ReaderInfo) { print("added \(readerInfo.name)") } func readerWasRemoved(_ readerInfo: any ReaderInfo) { print("removed \(readerInfo.name)") } func readerDidChange(_ readerInfo: any ReaderInfo, change: ReaderChange) { if change == .stateDidChange { print("state now \(readerInfo.state)") } } } ``` -------------------------------- ### Usage example from HomeView.swift Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mock-reader-ui.md Shows how to present and dismiss the mock reader in a view. It conditionally imports `MockReaderUI`, creates a `MockReaderUI` instance with the SDK, presents it if not already presented, and dismisses it. Errors are caught and printed. ```swift #if canImport(MockReaderUI) import MockReaderUI #endif // present do { if viewModel.mockReader == nil { self.viewModel.mockReader = try MockReaderUI(for: mobilePaymentsSDK) } if let mockReader = viewModel.mockReader, !mockReader.isPresented { try mockReader.present() } } catch { print("Mock Reader Error: \(error.localizedDescription)") } // dismiss viewModel.mockReader?.dismiss() #endif ``` -------------------------------- ### startPairing(with:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Starts the reader pairing flow with a delegate that receives pairing callbacks. Returns an optional PairingHandle that can be used to stop the pairing process. ```APIDOC ## startPairing(with:) ### Description Starts the reader pairing flow with a delegate that receives pairing callbacks. Returns an optional PairingHandle that can be used to stop the pairing process. ### Method Function ### Signature ```swift @discardableResult @objc func startPairing(with delegate: any ReaderPairingDelegate) -> (any PairingHandle)? ``` ### Parameters - **delegate** (`any ReaderPairingDelegate`) - Required - Receives `readerPairingDidBegin` / `readerPairingDidSucceed` / `readerPairingDidFail(with:)`. ### Returns `(any PairingHandle)?` — an optional handle you can call `stop()` on; `nil` if pairing could not start. Pairing failures arrive as `ReaderPairingError`. ### Usage Example ```swift final class PairingCoordinator: ReaderPairingDelegate { func readerPairingDidBegin() { print("started") } func readerPairingDidSucceed() { print("paired") } func readerPairingDidFail(with error: any Error) { print("pairing failed: \(error)") } } let handle = mobilePaymentsSDK.readerManager.startPairing(with: coordinator) ``` ``` -------------------------------- ### Usage example: AppDelegate initializing MobilePaymentsSDK Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mobile-payments-sdk.md Example from DonutCounterApp.swift showing how to initialize the SDK in the app delegate. It reads the application ID from Config and calls MobilePaymentsSDK.initialize, then stores the shared SDKManager. ```swift import SwiftUI import SquareMobilePaymentsSDK class AppDelegate: NSObject, UIApplicationDelegate { private(set) var mobilePaymentSDK: SDKManager! func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil ) -> Bool { guard let applicationId = Config.squareApplicationID else { fatalError("Replace the values in Config.swift with values from your Square account") } MobilePaymentsSDK.initialize(squareApplicationID: applicationId) self.mobilePaymentSDK = MobilePaymentsSDK.shared return true } } ``` -------------------------------- ### Usage example: TapToPaySettings linkAppleAccount Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Checks device capability and links an Apple account, printing an error if linking fails. ```swift let tapToPay = mobilePaymentsSDK.readerManager.tapToPaySettings guard tapToPay.isDeviceCapable else { return } tapToPay.linkAppleAccount { error in if let error { print("link failed: \(error)") } } ``` -------------------------------- ### startPayment method signature Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Starts a payment with the given parameters and prompt configuration. Returns an optional PaymentHandle for cancellation and inspection; nil if the payment could not be started. Fails via the delegate's didFail with PaymentError cases such as .paymentAlreadyInProgress, .notAuthorized, .timedOut. ```swift @discardableResult @objc func startPayment(_ paymentParameters: PaymentParameters, promptParameters: PromptParameters, from viewController: UIViewController, delegate: any PaymentManagerDelegate) -> (any PaymentHandle)? ``` -------------------------------- ### Run script phase for SquareMobilePaymentsSDK setup Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/index.md Mandatory run-script build phase that executes the setup executable from the SquareMobilePaymentsSDK framework. Place this phase after any embed frameworks phase. ```sh SETUP_SCRIPT=${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}"/SquareMobilePaymentsSDK.framework/setup" if [ -f "$SETUP_SCRIPT" ]; then "$SETUP_SCRIPT" fi ``` -------------------------------- ### Usage example for OfflinePaymentQueue Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-models.md Shows how to use getTotalStoredPaymentsAmount and getPayments to read the offline payment queue. ```swift let queue = mobilePaymentsSDK.paymentManager.offlinePaymentQueue queue.getTotalStoredPaymentsAmount { amount, error in if let error { print("failed to read queue: \(error)") } else if let amount { print("stored: \(amount.amount) \(amount.currency)") } } queue.getPayments { payments, error in payments.forEach { p in print("queued localID=\(p.localID) status=\(p.status)") } } ``` -------------------------------- ### Catch example for MockReaderUI errors Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md Example of catching errors when initializing and presenting MockReaderUI. Used by the sample app. Prints the localized error description on failure. ```swift do { let mockReader = try MockReaderUI(for: MobilePaymentsSDK.shared) try mockReader.present() } catch { print("Mock Reader Error: \(error.localizedDescription)") } ``` -------------------------------- ### Currency conversion usage example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/utilities.md Shows converting .USD to "USD" and "CAD" back to .CAD. ```swift let code = SQMPCurrencyCodeFromCurrency(.USD) // "USD" let currency = SQMPCurrencyFromCurrencyCode("CAD") // .CAD ``` -------------------------------- ### Deauthorize usage example Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/authorization.md Calls deauthorize and prints a message when deauthorization completes. ```swift mobilePaymentsSDK.authorizationManager.deauthorize { print("deauthorized") } ``` -------------------------------- ### PaymentParameters Instance Properties Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Properties of PaymentParameters that are validated by the SDK before the payment starts. ```APIDOC ## PaymentParameters Instance Properties ### Description Properties of PaymentParameters that are validated by the SDK before the payment starts. ### Properties - `idempotencyKey` (String) - Read-write - Attempt identifier. - `amountMoney` (any MoneyAmount) - Read-write - Sale amount. - `processingMode` (ProcessingMode) - Read-write - Online/offline/auto. - `createdAt` (Date) - Read-only - Creation timestamp. - `totalMoney` (any MoneyAmount) - Read-only (computed) - Computed total (amount + tip + app fee). - `autocomplete` (Bool) - Read-write - Auto-complete after capture. - `tipMoney` (any MoneyAmount?) - Read-write - Optional tip. - `appFeeMoney` (any MoneyAmount?) - Read-write - App fee to charge above the sale amount. - `referenceID` (String?) - Read-write - Application-level reference. - `note` (String?) - Read-write - Payment note. - `orderID` (String?) - Read-write - Square Order ID. - `customerID` (String?) - Read-write - Square Customer ID. - `teamMemberID` (String?) - Read-write - Team member (clerk) ID. - `locationID` (String?) - Read-write - Overrides the authorized location. - `statementDescriptionIdentifier` (String?) - Read-write - Bank statement descriptor. - `cardHandle` (any CardHandle?) - Read-write - Pre-read card (e.g. from ReadCardInfo) to charge. - `acceptPartialAuthorization` (Bool) - Read-write - Allow partial authorization. - `delayAction` (DelayAction) - Read-write - What to do after `delayDuration`. - `delayDuration` (TimeInterval) - Read-write - Delay before `delayAction`. ``` -------------------------------- ### Present and dismiss a mock reader with MockReaderUI Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/AGENTS.md Use this Swift snippet to present and dismiss a virtual Square reader in Sandbox. It requires the MockReaderUI framework and the MobilePaymentsSDK shared instance. Note that the published framework only exposes instantiation, present(), and dismiss(); there is no public API to add a reader or simulate card actions. ```swift #if canImport(MockReaderUI) let mockReader = try MockReaderUI(for: MobilePaymentsSDK.shared) try mockReader.present() // … mockReader.dismiss() #endif ``` -------------------------------- ### Error-handling example for PaymentManagerDelegate Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Delegate method that maps an (error as NSError).code back to PaymentError.rawValue and handles specific error cases. From Example/DonutCounter/DonutCounter/Screens/Home/HomeViewModel.swift. ```swift func paymentManager(_ paymentManager: PaymentManager, didFail payment: Payment, withError error: Error) { let paymentError = PaymentError(rawValue: (error as NSError).code) switch paymentError { case .paymentAlreadyInProgress, .notAuthorized, .timedOut: print(error) case .idempotencyKeyReused: print("Developer error: idempotency key reused; check recent payments' status.") default: print(error) } } ``` -------------------------------- ### Authorize usage example from PermissionsView.swift Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/authorization.md Guards on state == .notAuthorized before calling authorize. Uses the ObjC-selector-derived form authorize(withAccessToken:locationID:completion:). Prints error on failure. ```swift guard mobilePaymentsSDK.authorizationManager.state == .notAuthorized else { return } mobilePaymentsSDK.authorizationManager.authorize( withAccessToken: accessToken, locationID: locationId ) { error in if let error { print("Failed to authorize: \(error)") } } ``` -------------------------------- ### SDKManager.paymentManager Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mobile-payments-sdk.md Provides access to the payment manager, which handles starting and tracking payments. ```APIDOC ## [GET] SDKManager.paymentManager ### Description Provides access to the payment manager, which handles starting and tracking payments. ### Method GET ### Endpoint SDKManager.paymentManager ### Parameters #### Path Parameters - **none** - No parameters. ### Request Example ```swift let paymentMgr = sdkManager.paymentManager ``` ### Response #### Success Response (200) - **paymentManager** (any PaymentManager) - The payment manager instance. #### Response Example ```swift let paymentMgr: any PaymentManager = sdkManager.paymentManager ``` ``` -------------------------------- ### Initialize and Authorize MobilePaymentsSDK Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/AGENTS.md Initialize the SDK in the app delegate and authorize after permissions are granted. Guard on state == .notAuthorized to avoid ALREADY_AUTHORIZED error. Any manager call before authorization fails with NOT_AUTHORIZED. ```swift // 1. AppDelegate MobilePaymentsSDK.initialize(squareApplicationID: applicationId) // 3. after permissions are granted guard MobilePaymentsSDK.shared.authorizationManager.state == .notAuthorized else { return } MobilePaymentsSDK.shared.authorizationManager.authorize( withAccessToken: accessToken, locationID: locationID ) { error in if let error { print("Failed to authorize: \(error)") } } ``` -------------------------------- ### PaymentManagerDelegate Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Protocol for receiving payment lifecycle events from a PaymentManager. Implement this protocol to handle payment start, finish, failure, and cancellation events. ```APIDOC ## Protocol: PaymentManagerDelegate ### Description Protocol for receiving payment lifecycle events from a PaymentManager. Implement this protocol to handle payment start, finish, failure, and cancellation events. ### Methods #### paymentManager(_:didStart:) - **Signature**: `@objc optional func paymentManager(_ paymentManager: any PaymentManager, didStart payment: any Payment)` - **Required**: no - **Description**: Called when a payment starts. #### paymentManager(_:willFinish:) - **Signature**: `@objc optional func paymentManager(_ paymentManager: any PaymentManager, willFinish payment: any Payment)` - **Required**: no - **Description**: Called when a payment is about to finish. #### paymentManager(_:didFinish:) - **Signature**: `@objc func paymentManager(_ paymentManager: any PaymentManager, didFinish payment: any Payment)` - **Required**: yes - **Description**: Called when a payment finishes successfully. #### paymentManager(_:didFail:withError:) - **Signature**: `@objc func paymentManager(_ paymentManager: any PaymentManager, didFail payment: any Payment, withError error: any Error)` - **Required**: yes - **Description**: Called when a payment fails with an error. #### paymentManager(_:willCancel:) - **Signature**: `@objc optional func paymentManager(_ paymentManager: any PaymentManager, willCancel payment: any Payment)` - **Required**: no - **Description**: Called when a payment is about to be cancelled. #### paymentManager(_:didCancel:) - **Signature**: `@objc func paymentManager(_ paymentManager: any PaymentManager, didCancel payment: any Payment)` - **Required**: yes - **Description**: Called when a payment is cancelled. ### Parameters All methods take `paymentManager: any PaymentManager` and `payment: any Payment`. ``` -------------------------------- ### CocoaPods Podfile for SquareMobilePaymentsSDK Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/index.md CocoaPods installation using the SquareMobilePaymentsSDK and MockReaderUI pods. MockReaderUI is restricted to Debug configurations and requires SquareMobilePaymentsSDK to be present. ```ruby use_frameworks! pod "SquareMobilePaymentsSDK", "~> 2.7.0" pod "MockReaderUI", "~> 2.7.0", configurations: ['Debug'] # requires SquareMobilePaymentsSDK present ``` -------------------------------- ### init(for:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mock-reader-ui.md Initializes a MockReaderUI instance with the provided SDK manager. Throws an error if the version mismatches or the application ID is not sandbox. ```APIDOC ## Initializer: `init(for:)` ### Description Initializes a `MockReaderUI` instance with the provided SDK manager. Throws an error if the version mismatches or the application ID is not sandbox. ### Method `init(for:)` ### Parameters - **mobilePaymentsSDK** (`SDKManager`) - Required - The SDK manager for the mock reader UI to use; in most cases `MobilePaymentsSDK.shared`. ### Throws - `MockReaderUIError` - `versionMismatch` if the `MockReaderUI` version does not match the `SquareMobilePaymentsSDK` version, `invalidApplicationId` if not in a sandbox environment. ### Example ```swift let mockReaderUI = try MockReaderUI(for: MobilePaymentsSDK.shared) ``` ``` -------------------------------- ### present() Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mock-reader-ui.md Shows the floating action button that simulates a magstripe or contactless reader. Must be called after initialization and with a sandbox application ID. ```APIDOC ## Method: `present()` ### Description Shows the floating action button that simulates a magstripe or contactless reader. Must be called after initialization and with a sandbox application ID. ### Method `present()` ### Parameters None ### Example ```swift mockReaderUI.present() ``` ``` -------------------------------- ### Currency init?(rawValue:) and init?(_ description:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Initializes a Currency object from a raw UInt value or a string description. The string initializer is LosslessStringConvertible and returns unknown for unrecognized input. ```APIDOC ## [INIT] Currency init?(rawValue:) and init?(_ description:) ### Description Initializes a Currency object from a raw UInt value or a string description. The string initializer is LosslessStringConvertible and returns unknown for unrecognized input. ### Method INIT ### Signatures ```swift init?(rawValue: UInt) init?(_ description: String) // LosslessStringConvertible; unknown input -> unknown init(from decoder: any Decoder) throws ``` ### Parameters - **rawValue** (UInt) - Required - Raw currency value. - **description** (String) - Required - String description of the currency. - **decoder** (any Decoder) - Required - Decoder for decoding from a serialized format. ``` -------------------------------- ### present() Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mock-reader-ui.md Displays a floating action button on top of the application's UI. Throws an error if presentation fails. ```APIDOC ## present() ### Description Displays a floating action button on top of the application's UI. ### Method `@objc func present() throws` ### Throws - **MockReaderUIError** - Possible errors: `invalidApplicationId` (only visible with a sandbox application ID), `notAuthorized` (presented before authorization), `noScene` (no scene to attach to, scene-based apps), `unexpected`, `versionMismatch`. ``` -------------------------------- ### PaymentManager Protocol Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/types.md The PaymentManager protocol handles payment processing. It provides methods to start and manage payment transactions. ```APIDOC ## PaymentManager Protocol ### Description The PaymentManager protocol handles payment processing. It provides methods to start and manage payment transactions. ### Declaration `@objc(SQMPPaymentManager) protocol PaymentManager` ### Full Documentation See [payment-manager.md](api-reference/payment-manager.md) for complete details. ``` -------------------------------- ### PromptParameters init(mode:additionalMethods:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Initializes a PromptParameters object that configures the payment prompt behavior. Use this to specify the prompt mode and additional payment methods. ```APIDOC ## PromptParameters init(mode:additionalMethods:) ### Description Initializes a PromptParameters object that configures the payment prompt behavior. Use this to specify the prompt mode and additional payment methods. ### Method init ### Signature ```swift @objc init(mode: PromptMode, additionalMethods: AdditionalPaymentMethods) ``` ### Parameters - **mode** (PromptMode) - Required - `.default` (SDK prompt) or `.custom` (your own UI). - **additionalMethods** (AdditionalPaymentMethods) - Required - Extra methods beyond the primary card reader: `.all`, `.keyed`, `.tapToPay`, or combinations. ### Properties - `mode` (PromptMode) - The prompt mode. - `additionalMethods` (AdditionalPaymentMethods) - The additional payment methods. ``` -------------------------------- ### prepareToReadCardInfoOnce(storeSwipedCard:shouldReadPreInsertedCard:) method Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/read-card-info.md Prepares to read a card once without charging. Parameters: storeSwipedCard (whether a swiped card may be stored) and shouldReadPreInsertedCard (whether to read a pre-inserted card). Results arrive on the registered ReadCardInfoObserver. ```swift @objc func prepareToReadCardInfoOnce(storeSwipedCard: Bool, shouldReadPreInsertedCard: Bool) ``` -------------------------------- ### presentSettings(viewController:completion:) method Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Presents Square's built-in reader pairing/management UI. The completion receives nil on success or an error. The ObjC selector is presentSettingsWithViewController:completion:. ```swift @objc func presentSettings(viewController: UIViewController, completion: @escaping ((any Error)?) -> Void) ``` -------------------------------- ### MockReaderUI init(for:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Initializes a MockReaderUI instance for the given SDKManager. This is used for testing with a mock reader and requires a sandbox application ID. ```APIDOC ## [INIT] MockReaderUI init(for:) ### Description Initializes a MockReaderUI instance for the given SDKManager. This is used for testing with a mock reader and requires a sandbox application ID. ### Method INIT ### Signature ```swift @objc convenience init(for mobilePaymentsSDK: SDKManager) throws ``` ### Parameters - **mobilePaymentsSDK** (SDKManager) - Required - Usually `MobilePaymentsSDK.shared`. Requires sandbox application ID; throws `MockReaderUIError` (`versionMismatch`, `invalidApplicationId`, ...). ``` -------------------------------- ### MockReaderUIError enumeration declaration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mock-reader-ui.md Declares the `MockReaderUIError` enum with Objective-C name `SQMPMockReaderUIError`. Errors occur when initialization/presentation of MockReaderUI fails. Cases: `invalidApplicationId` (non-sandbox environment), `noScene` (no scene to attach, scene-based apps), `notAuthorized` (unauthorized presentation), `versionMismatch` (version mismatch between `MockReaderUI` and `SquareMobilePaymentsSDK`), `unexpected` (unexpected initialization error). Also exposes `init?(rawValue: Int)`, `var debugInfo: (code: String, message: String) { get }`, `var errorDescription: String? { get }`; conforms to `NSError`/`LocalizedError`/`Equatable`/`RawRepresentable` via the `SQMPMockReaderUIError` domain. ```swift @objc(SQMPMockReaderUIError) enum MockReaderUIError ``` -------------------------------- ### prepareToReadCardInfoOnce(storeSwipedCard:shouldReadPreInsertedCard:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/read-card-info.md Prepares the SDK to read a payment card without charging it. Results are delivered to the registered ReadCardInfoObserver. ```APIDOC ## [METHOD] prepareToReadCardInfoOnce(storeSwipedCard:shouldReadPreInsertedCard:) ### Description Prepares the SDK to read a payment card without charging it. Results are delivered to the registered ReadCardInfoObserver. ### Method prepareToReadCardInfoOnce ### Parameters #### Parameters - **storeSwipedCard** (Bool) - Required - Whether a swiped (magstripe) card may be stored, reflected on the resulting `CardHandle.isSwipedCardStored`. - **shouldReadPreInsertedCard** (Bool) - Required - Whether to read a card already inserted in a chip reader. ### Returns Void. Results arrive on the registered `ReadCardInfoObserver` (`readCardInfoDidSucceed(_:)` or `readCardInfoDidFail(_:)`). ### Example ```swift reader.prepareToReadCardInfoOnce(storeSwipedCard: false, shouldReadPreInsertedCard: true) ``` ``` -------------------------------- ### SettingsManager instance properties Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Read-only properties for payment and SDK-wide settings. ```swift @objc var paymentSettings: any PaymentSettings { get } @objc var sdkSettings: any SDKSettings { get } ``` -------------------------------- ### Money init(totaling:) usage Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Creates a Money instance by summing two Money values. ```swift let total = Money(totaling: Money(amount: 100, currency: .USD), Money(amount: 25, currency: .USD)) ``` -------------------------------- ### PaymentError (SQMPPaymentError) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/errors.md An enum representing errors delivered through PaymentManagerDelegate.paymentManager(_:didFail:withError:) and the reason startPayment may not start. It covers various failure conditions during payment processing. ```APIDOC ## PaymentError (SQMPPaymentError) ### Description An enum representing errors delivered through `PaymentManagerDelegate.paymentManager(_:didFail:withError:)` and the reason `startPayment` may not start. It covers various failure conditions during payment processing. ### Cases - `notAuthorized` - Triggered when payment is started before authorization completes (`NOT_AUTHORIZED`). - `paymentAlreadyInProgress` - Triggered when a payment is already running; the SDK takes one payment at a time. - `invalidPaymentParameters` - Triggered when `PaymentParameters` fails validation. - `invalidPaymentSource` - Triggered when the chosen `PaymentSource` fails `validate()`. - `idempotencyKeyReused` - Triggered when the same idempotency key is used a second time after a previous attempt. - `timedOut` - Triggered when the payment times out. - `unsupportedMode` - Triggered when `ProcessingMode` is not supported in this environment/configuration. - `noNetwork` - Triggered when there is no network and no offline fallback. - `merchantNotOptedIntoOfflineProcessing` - Triggered when offline processing is attempted but the merchant is not opted in. - `noNetworkAndMerchantNotOptedIntoOfflineProcessing` - Triggered when there is no network and offline processing is unavailable. - `sandboxUnsupportedForOfflineProcessing` - Triggered when offline processing is attempted in Sandbox (Sandbox supports only `.onlineOnly`). - `offlineTransactionAmountExceeded` - Triggered when the offline transaction is above `PaymentSettings.offlineTransactionAmountLimit`. - `offlineStoredAmountExceeded` - Triggered when the offline queue is at `PaymentSettings.offlineTotalStoredAmountLimit`. - `locationPermissionNeeded` - Triggered when location permission is required for the transaction but not granted. - `deviceTimeDoesNotMatchServerTime` - Triggered when device clock skew is detected. - `unexpected` - Triggered on internal or unexpected failure. ### Usage Delivered through the delegate method and as the reason `startPayment` may not start. Note: the shipped DocC archive names the reuse case `idempotencyKeyReused`; the sample app switches on `.paymentAttemptIdReused` (pre-2.7 naming) — in 2.7.0 compare against `.idempotencyKeyReused`. ``` -------------------------------- ### PromptParameters init(mode:additionalMethods:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Initializes a PromptParameters object to configure the payment prompt mode and additional payment methods. This is used to customize the SDK's prompt behavior. ```APIDOC ## [INIT] PromptParameters init(mode:additionalMethods:) ### Description Initializes a PromptParameters object to configure the payment prompt mode and additional payment methods. This is used to customize the SDK's prompt behavior. ### Method INIT ### Signature ```swift @objc init(mode: PromptMode, additionalMethods: AdditionalPaymentMethods) ``` ### Parameters - **mode** (PromptMode) - Required - `.default` (SDK prompt) or `.custom`. - **additionalMethods** (AdditionalPaymentMethods) - Required - Extra methods: `.all`, `.keyed`, `.tapToPay`, or combinations. ``` -------------------------------- ### Observer registration methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/authorization.md Adds or removes an AuthorizationStateObserver. Both methods return Void. ```swift @objc func add(_ authorizationStateObserver: any AuthorizationStateObserver) @objc func remove(_ authorizationStateObserver: any AuthorizationStateObserver) ``` -------------------------------- ### Money init(amount:currency:) usage Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Creates a Money instance representing $1.00 USD. ```swift let dollar = Money(amount: 100, currency: .USD) ``` -------------------------------- ### Money.init(totaling:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Initializes a Money value by summing a variadic list of money values. The resulting currency is that of the first value. ```APIDOC ## [Swift] Money.init(totaling:) ### Description Initializes a Money value by summing a variadic list of money values. The resulting currency is that of the first value. ### Method Initializer ### Signature `convenience init(totaling monies: (any MoneyAmount)?...)` ### Parameters - **monies** ((any MoneyAmount)?...) - Optional - Variadic list of money values to total. ### Returns `Money` - The summed amount in the currency of the first value. ### Usage Example ```swift let total = Money(totaling: Money(amount: 100, currency: .USD), Money(amount: 25, currency: .USD)) ``` ``` -------------------------------- ### SettingsManager.presentSettings(viewController:completion:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Presents Square's built-in reader pairing/management UI from the provided view controller. The completion handler returns nil on success or an error on failure. ```APIDOC ## [presentSettings(viewController:completion:)] ### Description Presents Square's built-in reader pairing/management UI from the provided view controller. The completion handler returns nil on success or an error on failure. ### Method presentSettings(viewController:completion:) ### Parameters - **viewController** (UIViewController) - Required - View controller to present the Settings screen from. - **completion** (((any Error)?) -> Void) - Required - nil on success, otherwise the presentation error. ### Request Example ```swift mobilePaymentsSDK.settingsManager.presentSettings( with: viewHolder.controller ) { error in if let error { print(error.localizedDescription) } } ``` ### Response #### Success Response - **Void** - No return value. #### Error Handling - **error** ((any Error)?) - nil on success, otherwise the presentation error. ``` -------------------------------- ### Trigger payment with a payment source Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-sources.md Shows how to use a payment source with AdditionalPaymentMethod.triggerPayment(with:). The source is obtained from the prompt's additional methods and validated before use. ```swift let method: any AdditionalPaymentMethod = promptHandle.additionalPaymentMethods.first { $0.type == .tapToPay }! do { try method.triggerPayment(with: tapToPaySource) } catch { print("failed to trigger: \(error)") } ``` -------------------------------- ### Money init(amount:currency:) declaration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Initializer for creating a Money instance with an amount and currency. ```swift @objc required init(amount: UInt, currency: Currency) ``` -------------------------------- ### TapToPaySettings.linkAppleAccount(completion:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Begins Apple account linking for Tap to Pay on iPhone. The completion handler returns nil on success or an error on failure. ```APIDOC ## [linkAppleAccount(completion:)] ### Description Begins Apple account linking for Tap to Pay on iPhone. The completion handler returns nil on success or an error on failure. ### Method linkAppleAccount(completion:) ### Parameters - **completion** (@escaping ((any Error)?) -> Void) - Required - nil on success, otherwise an error. ### Response #### Success Response - **Void** - No return value. #### Error Handling - **error** ((any Error)?) - nil on success, otherwise an error. ``` -------------------------------- ### Determine environment and processing mode at runtime Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Determines the environment at runtime (as the sample does). Uses `SDKSettings.environment` to set `ProcessingMode` to `.onlineOnly` for sandbox or `.autoDetect` for production. ```swift let environment = mobilePaymentsSDK.settingsManager.sdkSettings.environment let mode: ProcessingMode = environment == .sandbox ? .onlineOnly : .autoDetect ``` -------------------------------- ### Money init(totaling:) declaration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Convenience initializer that sums a variadic list of money values. ```swift convenience init(totaling monies: (any MoneyAmount)?...) ``` -------------------------------- ### Version Globals Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/utilities.md Version constants for the SDK and API generation. ```APIDOC ## Version Globals ### Description Version constants for the SDK and API generation. ### Constants - `var SquareMobilePaymentsSDKVersionNumber: Double` - `let SquareMobilePaymentsSDKVersionString: <>` - `var MobilePaymentsSDKAPIVersionNumber: Double` - `let MobilePaymentsSDKAPIVersionString: <>` `SquareMobilePaymentsSDKVersionNumber`/`...String` describe the 2.7.0 release; `MobilePaymentsSDKAPIVersionNumber`/`...String` describe the framework's API generation. ``` -------------------------------- ### SDKSettings protocol declaration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Objective-C–compatible protocol for SDK-wide settings. ```swift @objc(SQMPSDKSettings) protocol SDKSettings : NSObjectProtocol ``` -------------------------------- ### Observer registration methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Add or remove a ReaderObserver to receive reader change notifications. ```swift @objc func add(_ readerObserver: any ReaderObserver) @objc func remove(_ readerObserver: any ReaderObserver) ``` -------------------------------- ### MobilePaymentsSDK.initialize(applicationLaunchOptions:squareApplicationID:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mobile-payments-sdk.md Initializes the SDK with the Square application ID. Must be called before accessing shared. The applicationLaunchOptions parameter is optional and defaults to nil. ```swift @objc static func initialize(applicationLaunchOptions: [UIApplication.LaunchOptionsKey : Any]?, squareApplicationID: String) ``` -------------------------------- ### Money instance properties Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Declares the amount, currency, and description properties of Money. ```swift var amount: UInt var currency: Currency override var description: String { get } ``` -------------------------------- ### Money.init(amount:currency:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Initializes a Money value with a given amount in minor units and a currency. This is the primary way to create a money value. ```APIDOC ## [Swift] Money.init(amount:currency:) ### Description Initializes a Money value with a given amount in minor units and a currency. ### Method Initializer ### Signature `@objc required init(amount: UInt, currency: Currency)` ### Parameters - **amount** (UInt) - Required - Amount in the currency's minor units (e.g. `100` = $1.00 for `.USD`). - **currency** (Currency) - Required - Currency of the amount. ### Returns `Money` ### Usage Example ```swift let dollar = Money(amount: 100, currency: .USD) ``` ``` -------------------------------- ### Observer registration methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Adds or removes an observer for available card input methods. ```swift @objc func add(_ availableCardInputMethodsObserver: any AvailableCardInputMethodsObserver) @objc func remove(_ availableCardInputMethodsObserver: any AvailableCardInputMethodsObserver) ``` -------------------------------- ### Config.swift placeholder for credentials Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Placeholder file with all credential values set to nil. Fill in values from the Square Developer Console. ```swift public enum Config { static let squareApplicationID: String? = nil static let accessToken: String? = nil static let locationID: String? = nil } ``` -------------------------------- ### Money init(amount:currency:) and convenience init(totaling:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/configuration.md Initializes a Money object with an amount in minor units and a currency, or totals multiple MoneyAmount instances. This is used to represent monetary values in the SDK. ```APIDOC ## [INIT] Money init(amount:currency:) and convenience init(totaling:) ### Description Initializes a Money object with an amount in minor units and a currency, or totals multiple MoneyAmount instances. This is used to represent monetary values in the SDK. ### Method INIT ### Signatures ```swift @objc required init(amount: UInt, currency: Currency) convenience init(totaling monies: (any MoneyAmount)?...) ``` ### Parameters - **amount** (UInt) - Required - Minor-unit amount (`100` = $1.00). - **currency** (Currency) - Required - Currency case. - **monies** ((any MoneyAmount)?...) - Varies - Variadic inputs for the totalling initializer. ``` -------------------------------- ### PaymentSettings protocol declaration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Objective-C–compatible protocol for payment/offline-processing settings. ```swift @objc(SQMPPaymentSettings) protocol PaymentSettings : NSObjectProtocol ``` -------------------------------- ### Money instance properties Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/money-currency.md Properties of the Money class: amount, currency, and description. ```APIDOC ## [Swift] Money instance properties ### Description Properties of the Money class: amount, currency, and description. ### Properties - **amount** (UInt) - Minor-unit amount. - **currency** (Currency) - Currency. - **description** (String) - Human-readable description (`CustomStringConvertible`). ### Signatures ```swift var amount: UInt var currency: Currency override var description: String { get } ``` ``` -------------------------------- ### Environment enumeration declaration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/settings.md Objective-C–compatible enumeration for the SDK environment. ```swift @objc(SQMPEnvironment) enum Environment ``` -------------------------------- ### PaymentParameters Initializer Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-manager.md Initializes a PaymentParameters instance with required parameters for a payment attempt. ```APIDOC ## PaymentParameters Initializer ### Description Initializes a PaymentParameters instance with required parameters for a payment attempt. ### Method `init(idempotencyKey: String, amountMoney: any MoneyAmount, processingMode: ProcessingMode)` ### Parameters - `idempotencyKey` (String) - Required - Unique attempt ID. DocC selector: `initWithIdempotencyKey:amountMoney:processingMode:`. The sample app calls this parameter `paymentAttemptID` — derive both from an order/sale identifier to prevent duplicate payments on retry. Reusing a key after a previous attempt errors with `.idempotencyKeyReused`. - `amountMoney` (any MoneyAmount) - Required - Sale amount (e.g. `Money(amount: 100, currency: .USD)` for $1.00). - `processingMode` (ProcessingMode) - Required - `.onlineOnly`, `.offlineOnly`, or `.autoDetect`. Sandbox supports only `.onlineOnly`. ``` -------------------------------- ### Reader management methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Methods to blink, forget, or retry connection for a reader. Each takes a ReaderInfo and returns Void. ```swift @objc func blink(_ readerInfo: any ReaderInfo) @objc func forget(_ readerInfo: any ReaderInfo) @objc func retryConnection(_ readerInfo: any ReaderInfo) ``` -------------------------------- ### ReaderManager instance properties Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Properties for accessing known readers, pairing status, and Tap to Pay settings. ```swift @objc var readers: [any ReaderInfo] { get } @objc var isPairingInProgress: Bool { get } @objc var tapToPaySettings: any TapToPaySettings { get } ``` -------------------------------- ### ReaderPairingDelegate.readerPairingDidFail(with:) Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/reader-manager.md Called when the reader pairing process fails. Provides an error object describing the failure. ```APIDOC ## ReaderPairingDelegate.readerPairingDidFail(with:) ### Description Called when the reader pairing process fails. Provides an error object describing the failure. ### Method readerPairingDidFail(with:) ### Parameters - **error** (any Error) - Required - The error that caused the failure. ### Returns Void ``` -------------------------------- ### CashPaymentSource class declaration Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/payment-sources.md Creates a new payment using cash. The shipped DocC archive declares the class but exposes no public initializer or members beyond the inherited validate(). ```swift @objc(SQMPCashPaymentSource) class CashPaymentSource ``` -------------------------------- ### present() method Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/mock-reader-ui.md Displays a floating action button on top of the application's UI. Throws `MockReaderUIError` with cases: `invalidApplicationId` (only visible with a sandbox application ID), `notAuthorized` (presented before authorization), `noScene` (no scene to attach to, scene-based apps), `unexpected`, `versionMismatch`. ```swift @objc func present() throws ``` -------------------------------- ### Observer registration methods Source: https://github.com/square/mobile-payments-sdk-ios/blob/main/_autodocs/api-reference/read-card-info.md Adds or removes a ReadCardInfoObserver to receive card read results. ```swift @objc func add(_ readCardInfoObserver: any ReadCardInfoObserver) ``` ```swift @objc func remove(_ readCardInfoObserver: any ReadCardInfoObserver) ```