Reader SDK

Build on iOS

Build with Reader SDK on iOS to process in-person payments with Square hardware.

iOS
Reader SDK

Prerequisites and assumptions
Permalink Get a link to this section

To build with Reader SDK, the following must be true:

  • You have a Square Account enabled for payment processing. If you have not enabled payment processing on your account (or you are not sure), visit squareup.com/activate.

  • You are using Xcode 10.2+

  • You have set your Xcode iOS Deployment Target to iOS 11

Note

If you need to support iOS 10, you must restrict build architectures to arm64 using the following steps:

  1. Open the Build Settings tab for your target in Xcode.

  2. Set the Architectures and Valid Architectures values to arm64.

  3. Open your Info.plist file in Xcode.

  4. Set UIRequiredDeviceCapabilities to arm64.

Your app will not be able to run on a device that does not support 64-bit code.


Additionally, this guide makes the following assumptions:

  • Your version of Reader SDK adheres to the Square update policy. To limit risk to developers and their users, Square enforces an update policy for Reader SDK requiring developers keep their version of Reader SDK current.

  • You are generally familiar with developing apps on iOS. If you are new to iOS development, we recommend reading the Getting Started with iOS Development guide at the Apple Training center before continuing.

Information you will need
Permalink Get a link to this section

To use the steps in this guide you will need the following information:

  • Your application ID. Find your application ID on the Credentials setting page of your Square application.

  • Your Reader SDK repo password. Find your Reader SDK repo password on the Reader SDK setting page of your Square application.

Step 1: Request Reader SDK credentials
Permalink Get a link to this section

  1. Open the Square Application Dashboard. You will be prompted to login or create a new account.

  2. Create a new Square application.

  3. Click on the new application to bring up the Square application settings pages.

  4. Open the Reader SDK page and click "Request Credentials" to generate your Reader SDK repository password.

readersdk-settings-page

Step 2: Install Reader SDK
Permalink Get a link to this section

Download and configure the latest version of SquareReaderSDK.framework in your project root. The framework is installed in the current directory:

ruby <(curl https://connect.squareup.com/readersdk-installer) install \
--app-id SQUARE_READER_SDK_APPLICATION_ID                             \
--repo-password SQUARE_READER_SDK_REPOSITORY_PASSWORD

Step 3: Configure your iOS project for Reader SDK
Permalink Get a link to this section

Add a Reader SDK build phase
Permalink Get a link to this section

  1. Add Reader SDK to your project:

  • Open the General tab for your app target in Xcode.

  • Drag the newly downloaded SquareReaderSDK.framework into the Embedded Binaries section and click "Finish" in the modal that appears.

  1. Open the Xcode workspace or project for your application.

  2. In the Build Phases tab for your application target, click the + button (at the top of the pane).

  3. Select New Run Script Phase.

  4. Paste the following into the editor panel of the new run script:

FRAMEWORKS="${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}"
"${FRAMEWORKS}/SquareReaderSDK.framework/setup"

Important

To avoid "No such file or directory" build errors, make sure the Reader SDK Run Script phase is the last phase in the list.

Disable Bitcode
Permalink Get a link to this section

Reader SDK does not currently support bitcode. To disable Bitcode:

  1. Open the Build Settings tab for your application target.

  2. In the top right search field, search for 'bitcode'.

  3. Change the value of Enable Bitcode to NO.

Embed Swift Libraries
Permalink Get a link to this section

If your application target is pure Objective-C and contains no Swift code, you must include the standard Swift libraries with your application. To do this:

  1. Open the Build Settings tab for your application target.

  2. In the top right search field, search for 'embed swift'.

  3. Change the value of Always Embed Swift Standard Libraries to Yes.

Add support for required interface orientations
Permalink Get a link to this section

In Xcode, open the General tab for your app target and make sure the Landscape Left and Landscape Right device orientations are supported:

ios-device-orientation

If your application runs on iPhone, it must support portrait and landscape interface orientations so that Reader SDK can display the signature screen during checkout.

If you want specific screens in your app to only support the portrait orientation, you can override the supportedInterfaceOrientations method in your UIViewController subclasses.

Update your Info.plist
Permalink Get a link to this section

Add or update the following key/value pairs in the Info tab for your application target to explain why your application requires these device permissions. Xcode may display human-readable labels (e.g., "Privacy - Microphone Usage Description") rather than the raw keys.

KeyDescription
NSLocationWhenInUseUsageDescriptionThis app integrates with Square for card processing. To protect buyers and sellers, Square requires your location to process payments.
NSMicrophoneUsageDescriptionThis app integrates with Square for card processing. To swipe magnetic cards via the headphone jack, Square requires access to the microphone.
NSBluetoothPeripheralUsageDescriptionThis app integrates with Square for card processing. Square uses Bluetooth to connect your device to compatible hardware.
NSCameraUsageDescriptionThis app integrates with Square for card processing. Upload your account logo, feature photo and product images with the photos stored on your mobile device.
NSPhotoLibraryUsageDescriptionThis app integrates with Square for card processing. Upload your account logo, feature photo and product images with the photos stored on your mobile device.
NSBluetoothAlwaysUsageDescriptionThis app integrates with Square for card processing. Square uses Bluetooth to connect your device to compatible hardware.

Note

Your application does not need to request Bluetooth, Camera, or Photo Library permissions to use Reader SDK. The usage descriptions are required due to the way Reader SDK is built.

Step 4: Request location permission
Permalink Get a link to this section

Add code to ensure your app has permission to use location services before starting a checkout flow. The location permission is managed by Apple's CLLocationManager class.

import CoreLocation

class YourViewController: UIViewController {
    private lazy var locationManager = CLLocationManager()

    func requestLocationPermission() {
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .restricted, .denied:
            print("Show UI directing the user to the iOS Settings app")
        case .authorizedAlways, .authorizedWhenInUse:
            print("Location services have already been authorized.")
        }
    }
}

Step 5: Request microphone permission
Permalink Get a link to this section

Add code to ensure your app has permission to access the microphone before starting checkout. The microphone permission is managed by Apple's AVAudioSession class. You must have the record permission from AVAudioSession in order to use Square's magstripe readers.

import AVFoundation

extension <#YourViewController#> {
    func requestMicrophonePermission() {
        // Note: The microphone permission prompt will not be displayed
        // when running on the simulator
        AVAudioSession.sharedInstance().requestRecordPermission { authorized in
            if !authorized {
                print("Show UI directing the user to the iOS Settings app")
            }
        }
    }
}

Step 6: Add code to initialize Reader SDK
Permalink Get a link to this section

Update the application:didFinishLaunchingWithOptions: method in your app delegate to initialize Reader SDK:

import SquareReaderSDK

func application(
    _: UIApplication,
    didFinishLaunchingWithOptions launchOptions:
    [UIApplicationLaunchOptionsKey: Any]? = nil
) -> Bool {
    SQRDReaderSDK.initialize(applicationLaunchOptions: launchOptions)

    return true
}

Step 7: Add code to request a mobile authorization code
Permalink Get a link to this section

Reader SDK requires a mobile authorization code from the Mobile Authorization API. Mobile authorization codes allow custom mobile apps to process payments on Square hardware on behalf of a specific Square account for a given location.

Mobile authorization codes are short lived and should be used immediately to authorize Reader SDK. Authorization is valid until it is explicitly revoked by calling deauthorize or your application fails to take a payment within 90 days. Mobile authorization codes do not need to be manually refreshed under normal operations.

Did you know?

Production apps should request mobile authorization codes programmatically, but you can also generate mobile authorization codes on the Reader SDK page of your application settings or manually with cURL during development.

Create a function, retrieveAuthorizationCode, to handle the work of calling your authorization service and handling the result:

import SquareReaderSDK

func retrieveAuthorizationCode() -> String {
    // TODO: Add code to retrieve a mobile authorization code.
    return "<Mobile Authorization Code>"
}

Step 8: Add code to authorize Reader SDK
Permalink Get a link to this section

import SquareReaderSDK

func authorizeReaderSDKIfNeeded() {
    if SQRDReaderSDK.shared.isAuthorized {
        print("Already authorized.")
    } else {
        let authCode = retrieveAuthorizationCode()
        SQRDReaderSDK.shared.authorize(withCode: authCode) { _, error in

            if let authError = error {
                // Handle the error
                print(authError)
            } else {
                // Proceed to the main application interface.
            }
        }
    }
}

Step 9: Implement CheckoutControllerDelegate methods
Permalink Get a link to this section

Your view controller must conform to the SQRDCheckoutControllerDelegate protocol to handle results and errors from the checkout flow. In most cases, your view controller should implement SQRDCheckoutControllerDelegate. If you choose to implement the delegate as a separate object, make sure it is retained until the checkout flow completes.

import SquareReaderSDK

extension <#YourViewController#>: SQRDCheckoutControllerDelegate {
    func checkoutControllerDidCancel(
        _: SQRDCheckoutController
    ) {
        print("Checkout cancelled.")
    }

    func checkoutController(
        _: SQRDCheckoutController, didFailWith _: Error
    ) {
        // TODO: Handle checkout errors
    }

    func checkoutController(
        _: SQRDCheckoutController,
        didFinishCheckoutWith _: SQRDCheckoutResult
    ) {
        // TODO: Handle checkout success
    }
}

Step 10: Add code to start the checkout flow
Permalink Get a link to this section

Create a SQRDCheckoutParameters object. At a minimum, you need to set the amount of money to be charged. Then, start the checkout flow by instantiating a Square Checkout controller (SQRDCheckoutController) and presenting it.

import SquareReaderSDK

extension <#YourViewController#> {
    func startCheckout() {
        // Create a money amount in the currency of the authorized Square account
        let amountMoney = SQRDMoney(amount: 100)

        // Create parameters to customize the behavior of the checkout flow.
        let params = SQRDCheckoutParameters(amountMoney: amountMoney)
        params.additionalPaymentTypes = [.cash, .manualCardEntry]

        // Create a checkout controller and call present to start checkout flow.
        let checkoutController = SQRDCheckoutController(
            parameters: params,
            delegate: self
        )
        checkoutController.present(from: self)
    }
}

Step 11: Add code to handle the checkout result
Permalink Get a link to this section

Implement the success and failure delegate methods. For now, we will print the checkout result to the Xcode console on success and error information on failure.

Reader SDK provides error types for all failable operations. For example, errors that occur while presenting the checkout flow will always be of type SQRDCheckoutControllerError. Error objects always contain user displayable details (error code and description) and debugging information (debug code and debug message).

// Success delegate method
func checkoutController(
    _: SQRDCheckoutController,
    didFinishCheckoutWith result: SQRDCheckoutResult
) {
    // result contains details about the completed checkout
    print("Checkout completed: \(result.description).")
}

// ...
// Failure delegate method
func checkoutController(
    _: SQRDCheckoutController, didFailWith error: Error
) {
    // Checkout controller errors are always of type SQRDCheckoutControllerError
    let checkoutControllerError = error as! SQRDCheckoutControllerError

    switch checkoutControllerError.code {
    case .sdkNotAuthorized:
        // Checkout failed because the SDK is not authorized
        // with a Square merchant account.
        print("Reader SDK is not authorized.")
    case .usageError:
        // Checkout failed due to a usage error. Inspect the userInfo
        // dictionary for additional information.
        if let debugMessage = checkoutControllerError.userInfo[SQRDErrorDebugMessageKey],
            let debugCode = checkoutControllerError.userInfo[SQRDErrorDebugCodeKey] {
            print(debugCode, debugMessage)
        }
    }
}

Testing Reader SDK on iOS
Permalink Get a link to this section

Reader SDK provides a Testing module that contains additional initializers that are not exposed in the Reader SDK framework. You can use these initializers to construct mock objects in your tests. For example, you might initialize a SQRDCard object in a unit test and use it to verify the behavior of your application.

import SquareReaderSDK.Testing // import the Testing module

func test_updateWithCard() {
    let card = SQRDCard(brand: .visa, lastFour: "1111")
    self.cardView.updateWithCard(card)

    XCTAssertEqualObjects(self.cardView.lastFourLabel.text, "1111")
    XCTAssertEqualObjects(self.cardView.brandLabel.text, "Visa")
}

Next steps

Now that you have a basic build in place, expand on it with these recipes!