iOS SDK

Overview

Cardknox iOS SDK is a mobile SDK targeted towards Objective C / Swift mobile application developers; it allows developers to process transactions with the Cardknox Transactions API.

Due to the necessity of the API key in this integration method, we strongly recommend reserving these features for integrations to be used solely on merchant-owned devices.

Getting started

To start, download the SDK framework file:

Integrate the framework file into your XCode project by referring to the technical documentation.

Choose your integration path

The SDK offers developers a couple of ways to process transactions:

  • In scope function

  • Out of scope function

  • Custom UI set of functions

Out of scope

Use the out of scope function when the user needs to provide their credit card information. This function displays the SDK user interface, effectively giving the control over to the SDK to acquire the sensitive credit card data from the user. The user provides the sensitive information either via a form or via a credit card device, and then the SDK processes the transaction with the gateway.

In scope

Use the in scope function when there is no need for the SDK to interact with the user through a user interface. The developer should either pass in a card number + an expiration date, or provide a tokenized card data via the xToken parameter to this function to quickly process the transaction and retrieve back the results.

Custom UI

Custom-UI integration consists of a set of functions to control the card reader device via the SDK. Currently supported card reader device is a Bluetooth VP3300 card reader. This integration path is useful when the developer has an existing UI and wishes to use a card reader device to obtain users' card sensitive information and then process the transaction with the gateway. The SDK offers a set of functions to control the card reader device. The SDK takes care of processing with the gateway and notifying the Developer’s application with the processing results.

The SDK offers the following functions: “start scanning for devices”, “stop scanning for devices”, “connect to device”, “disconnect from device”, “start transaction”, “stop transaction”.

Transaction workflows

Click here to view the transaction workflows online.

Download our sample applications:

Basic parameters

Basic parameter functions

Prior to any processing, the Cardknox SDK needs to be configured with user’s metadata and the account key. These functions can be called anywhere in the application any number of times to change the metadata and/or current account key.

Transaction required parameters

Each integration path has a “process” function that accepts a “transaction parameters” object. Developers specify required values for transaction processing through that object. Same object can be used to specify optional parameters to associate with a transaction; such as invoice numbers, billing address, etc.

Transaction optional parameters

Optional transaction parameters further complement the transaction processing. All the parameters are being sent to the Gateway during processing.

Retrieving results with callbacks

The SDK can notify the application about various events during processing, such as about different card reader events during out of scope processing, or perhaps about a completed bluetooth device scan during custom UI processing.

Developers opt in to receive callbacks by subscribing to the NSNotificationCenter using one of its' methods, using a predefined value from the SDK for the “name” parameter.

The SDK uses the same “name” value to report results & various information back to subscribers.

Available callback types and integrations where they are applicable in are as follows:

Callback subscriptions & result handling

Based on your integration path choice, choose an available callback type for that integration path and subscribe with the NSNotificationCenter to receive appropriate information back from the SDK.

Transaction result callback subscription

This callback delivers a “transaction processed response” object to the subscriber.

For Swift applications using Swift UI, subscription can be made in a View as follows:

import SwiftUI

struct ProcessOutOfScopeView: View 
{
  // Define a Publisher
  let transactionPublisher =
  NotificationCenter.default.publisher(for: NSNotification.Name(CardknoxSDK.transactionResultSubscription_NSNotificationCenterName()))

  var body: some View
  {
    VStack{}
    // Subscribe the Publisher with the NotificationCenter
    .onReceive(transactionPublisher, perform: transactionNotification)
  }
  
  // Define a function that accepts a Notification.
  // This method will be invoked when the SDK sends transaction processing results
  func transactionNotification(notif: Notification) {
  
    // Use the SDK's "response" object utility method to transform a Notification into a "response" object
    let response = PaymentTransactionResponse.unwrap(notif) as! PaymentTransactionResponse
  
    if response.isSuccess()
    {
        // Transaction successfully processed
        let errorMessage = response.errorMessage()!
        let refNum = response.xRefNum()!
        // ... other properties ...
    } else {
        // Transaction processing resulted in an error message which can be extracted from this property:
        let errorMessage = response.errorMessage()!
        let errorCode = response.xErrorCode()!
        let error = response.xError()!
    }
  }
}

For Swift and Objective-C applications using Storyboard, subscriptions can be made in the appropriate UIViewController lifecycle method:

import UIKit

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated);       
      let _notificationCenter = NotificationCenter.default        
      _notificationCenter.addObserver(self,
                                      selector: #selector(transactionNotification(aNotification:)),
                                      name: Notification.Name(CardknoxSDK.transactionResultSubscription_NSNotificationCenterName()),
                                      object: nil)
    }
    
    // Define a function that accepts a Notification.
    // This method will be invoked when the SDK sends transaction processing results
    @objc func transactionNotification(aNotification : Notification) {
        // Use the SDK's "response" object utility method to transform a Notification into a "response" object
        let response = PaymentTransactionResponse.unwrap(aNotification) as! PaymentTransactionResponse

        if response.isSuccess()
        {
            // Transaction successfully processed
            let errorMessage = response.errorMessage()!
            let refNum = response.xRefNum()!
            // ... other properties ...
        } else {
            // Transaction processing resulted in an error message which can be extracted from this property:
            let errorMessage = response.errorMessage()!
            let errorCode = response.xErrorCode()!
            let error = response.xError()!
        }
    }
}

Card reader event callback subscription

This callback delivers information about various events happening between the application & the card reader.

For example, while out-of-scope processing the SDK can report back error events related to bluetooth device pairing, such as “bluetooth not turned on” to indicate that the mobile device wanted to use the bluetooth service to find a near card reader device but the service is unavailable, or an error such as “waiting for device bluetooth response” to indicate that the mobile device found an eligible bluetooth card reader device, and is expecting the card reader to respond back with bluetooth data. This could mean that the bluetooth button on the card reader needs to be pressed.

After an established bluetooth pair, the SDK reports back events related to obtaining the card data via the card reader. For example, a “connected” event means that the mobile device & the card reader are connected and a card data transaction can start. A “transaction started” event means that the SDK initiated a card data transaction with the card reader and the physical card can be tapped onto the card reader.

For Swift applications using Swift UI, subscription can be made in a View as follows:

import SwiftUI

struct ProcessOutOfScopeView: View 
{
  // Define a Publisher
  let cardReaderEventPublisher =
  NotificationCenter.default.publisher(for: NSNotification.Name(CardknoxSDK.cardreaderEventSubscription_NSNotificationCenterName()))
  
  var body: some View
  {
    VStack{}
    // Subscribe the Publisher with the NotificationCenter
    .onReceive(cardReaderEventPublisher, perform: cardReaderEventNotification)
  }
  
  // Define a function that accepts a Notification.
  // This method will be invoked when the SDK sends card reader events
  func cardReaderEventNotification(aNotification: Notification){
    // Use the SDK's "response" object utility method to transform a Notification into a "response" object
    let callback = CardknoxCardReaderCallback.unwrap(aNotification) as! CardknoxCardReaderCallback
    
    // Read the event code
    let code : Int32 = callback.code();
    // Read the event name
    let name: String = callback.name()!;
    
    NSLog(String(format: "Card reader - %@", name));
    
    // Match the non-error code
    if(code == CardknoxCardReaderCallbackType.connected())
    {
        NSLog("Connected!");
    }
    
    // Match the error code & get the message
    if(code == CardknoxCardReaderCallbackType.error())
    {
        let errorMessage : String = callback.message()!;
        NSLog(String(format: "Card reader - %@", errorMessage));
    }
  }
}

For Swift and Objective-C applications using Storyboard, subscriptions can be made in the appropriate UIViewController lifecycle method:

import UIKit

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated);       
      let _notificationCenter = NotificationCenter.default        
      _notificationCenter.addObserver(self,
                                      selector: #selector(cardReaderEventNotification(aNotification:)),
                                      name: Notification.Name(CardknoxSDK.cardreaderEventSubscription_NSNotificationCenterName()),
                                      object: nil)
    }
    
    // Define a function that accepts a Notification.
    // This method will be invoked when the SDK sends card reader events
    @objc func cardReaderEventNotification(aNotification : Notification) {
        // Use the SDK's "response" object utility method to transform a Notification into a "response" object
        let callback = CardknoxCardReaderCallback.unwrap(aNotification) as! CardknoxCardReaderCallback
        
        // Read the event code
        let code : Int32 = callback.code();
        // Read the event name
        let name: String = callback.name()!;
        
        NSLog(String(format: "Card reader - %@", name));
        
        // Match the non-error code
        if(code == CardknoxCardReaderCallbackType.connected())
        {
            NSLog("Connected!");
        }
        
        // Match the error code & get the message
        if(code == CardknoxCardReaderCallbackType.error())
        {
            let errorMessage : String = callback.message()!;
            NSLog(String(format: "Card reader - %@", errorMessage));
        }
    }
}

Card reader events

When a card reader event happens, the SDK delivers an object, of a type named similarly to “CardknoxCardReaderCallback”, back into the app.

The object encapsulates two things:

  • an event integer code

  • an event name; such as “connected”, “disconnected”, etc.

Event integer codes are enumerated in a type named similarly to "CardknoxCardReaderCallbackType".

Developer can match the received integer code value with the enumeration of interest to pinpoint a wanted event.

Scanned bluetooth device callback subscription

One of the Custom UI integration functions is a “start scanning” function. The function keeps scanning for nearby bluetooth devices until it is manually stopped with the “stop scanning” function or if it times out.

During the scanning process, for every scanned device the SDK sends a “scanned device” object that contains all the necessary metadata about the scanned device, such as the devices' display name or its internal name.

For Swift applications using Swift UI, subscription can be made in a View as follows:

import SwiftUI

struct CustomUIView: View 
{
  // Track a scanned device
  @State private var scannedDevice : CardknoxSDKCustomUIScannedDevice!;
  
  // Define a Publisher
  let customUIscannedDeviceSubscription =
  NotificationCenter.default.publisher(for: NSNotification.Name(CardknoxSDKCustomUI.customUI_scannedDevice_Subscription_NSNotificationCenterName()))
  
  var body: some View
  {
    VStack{}
    // Subscribe the Publisher with the NotificationCenter
    .onReceive(customUIscannedDeviceSubscription, perform: customUIscannedDeviceSubscription)
}
  
  // Define a function that accepts a Notification.
  // This method will be invoked when the SDK sends scanned device information
  func customUIscannedDeviceSubscription(aNotification: Notification){
      // Use the SDK's "response" object utility method to transform a Notification into a "response" object
      scannedDevice = CardknoxSDKCustomUIScannedDevice.from(aNotification) as! CardknoxSDKCustomUIScannedDevice;
      let name = scannedDevice.name();
      let displayName = scannedDevice.displayName();
      let uuid = scannedDevice.uuid();
  }
}

For Swift and Objective-C applications using Storyboard, subscriptions can be made in the appropriate UIViewController lifecycle method:

import UIKit

class ViewController: UIViewController {
    // Track a scanned device
    private var scannedDevice : CardknoxSDKCustomUIScannedDevice!;
    
    override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated);       
      let notificationCenter = NotificationCenter.default
            notificationCenter.addObserver(self, selector: #selector(customUIScannedDeviceSubscription(aNotification:)), name: Notification.Name( CardknoxSDKCustomUI.customUI_scannedDevice_Subscription_NSNotificationCenterName()), object: nil)
    }
    
    // Define a function that accepts a Notification.
    // This method will be invoked when the SDK sends scanned device information
    @objc func scannedDeviceNotification(aNotification : Notification) {
        // Use the SDK's "response" object utility method to transform a Notification into a "response" object
        let scannedDevice = CardknoxSDKCustomUIScannedDevice.from(aNotification) as! CardknoxSDKCustomUIScannedDevice;
        let name = scannedDevice.name();
        let displayName = scannedDevice.displayName();
        let uuid = scannedDevice.uuid();
        
        // Uuid can be used to connect to the device, like this:
        let exampleCustomUI: CardknoxSDKCustomUI? = nil;
        exampleCustomUI?.connect(withUUID: uuid);
    }
}

Scan completed callback subscription

One of the Custom UI integration functions is a “start scanning” function. The function keeps scanning for nearby bluetooth devices until it is manually stopped with the “stop scanning” function or if it times out.

Once the scanning process ends, the SDK sends a list of scanned device objects to all subscribers. Any object in the retrieved list can be used as an argument to the “connect to device” method.

For Swift applications using Swift UI, subscription can be made in a View as follows:

import SwiftUI

struct CustomUIView: View 
{
  // Track a scanned device
  @State private var scannedDevice : CardknoxSDKCustomUIScannedDevice!;
  
  // Define a Publisher
  let customUIscanCompletedSubscription =
  NotificationCenter.default.publisher(for: NSNotification.Name(CardknoxSDKCustomUI.customUI_scanCompleted_Subscription_NSNotificationCenterName()))
  
  var body: some View
  {
    VStack{}
    // Subscribe the Publisher with the NotificationCenter
    .onReceive(customUIscanCompletedSubscription, perform: customUIscanCompletedNotification(aNotification:))
  }
  
  // Define a function that accepts a Notification.
  // This method will be invoked when the SDK stops the scanning process and sends back all scanned devices
  func customUIscanCompletedNotification(aNotification: Notification){
      let scanCompleted = CardknoxSDKCustomUIScanCompleted.from(aNotification) as! CardknoxSDKCustomUIScanCompleted;
      let devices : Array<Any> = scanCompleted.scannedDevices();
      
      // Example to get a first scanned VP3300 device.
      // All VP3300 devices have their internal name start with IDTECH prefix
      if(devices != nil && devices.count > 0)
      {
          for dev in devices{
              let typedDevice = dev as! CardknoxSDKCustomUIScannedDevice
              let name = typedDevice.name()!;
              
              if name.hasPrefix("IDTECH")
              {
                  // Save the reference & use it with the "connect to device" method
                  scannedDevice = typedDevice;
                  break;
              }
          }
      }
  }
}

For Swift applications using Storyboard, subscriptions can be made in the appropriate UIViewController lifecycle method. For Objective C applications, subscriptions can be made in the appropriate UIViewController lifecycle method:

import UIKit

class ViewController: UIViewController {
    
    override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated);       
      let notificationCenter = NotificationCenter.default        
      notificationCenter.addObserver(self, selector: #selector(customUIScanCompletedSubscription(aNotification:)), name: Notification.Name( CardknoxSDKCustomUI.customUI_scanCompleted_Subscription_NSNotificationCenterName()), object: nil)
    }
    
    // Define a function that accepts a Notification.
    // This method will be invoked when the SDK stops the scanning process and sends back all scanned devices
    @objc func scanCompletedNotification(aNotification: Notification){
        let scanCompleted = CardknoxSDKCustomUIScanCompleted.from(aNotification) as! CardknoxSDKCustomUIScanCompleted;
        let devices : Array<Any> = scanCompleted.scannedDevices();
        var scannedDevice: CardknoxSDKCustomUIScannedDevice? = nil;
        
        // Example to get a first scanned VP3300 device.
        // All VP3300 devices have their internal name start with IDTECH prefix
        if(devices != nil && devices.count > 0)
        {
            for dev in devices{
                let typedDevice = dev as! CardknoxSDKCustomUIScannedDevice
                let name = typedDevice.name()!;
                
                if name.hasPrefix("IDTECH")
                {
                    // Save the reference & use it with the "connect to device" method
                    scannedDevice = typedDevice;
                    break;
                }
            }
        }
    }
}

Out of scope integration

Out of scope processing feature allows the developer to show the Cardknox user interface for payment processing.

First, create an “out of scope” or “ui” manager kind of object. This object can create “request” objects that are capable of showing the SDK’s user interface:

let cardknoxSDKUI : CardknoxSDKUI = CardknoxSDKUI.create() as! CardknoxSDKUI;
CardknoxSDKUI* cardknoxUI = [CardknoxSDKUI create];

The developer is responsible for the CardknoxSDKUI object instance. Once the object is no longer needed, the method named similar to destroy needs to be called. A good place to maintain the object are “appear” and “disappear” callbacks.

import SwiftUI
struct MyView: View {
  @State private var cardknoxUI : CardknoxSDKUI!;
  
  var body: some View{
    Label(title: {Text("Hello world")}, icon: {})
        .onAppear(perform:onAppearFunc)
        .onDisappear(perform:onDisappear)
  }
  
  func onAppearFunc(){
      CardknoxSDK.setPrincipalKey("Your xKey")
      CardknoxSDK.setxSoftwareName("Your app name", xSoftwareVersion: "1.0.0", xVersion: "4.5.9")
      cardknoxUI = CardknoxSDKUI.create() as! CardknoxSDKUI;
  }
  
  func onDisappear(){
      if(cardknoxUI != nil){
          cardknoxUI.destroy();
      }
      cardknoxUI = nil;
  }
}

To show the user interface, create a request object that is capable of showing a user interface:

// Create the parameters object
let prms : TransactionParameters = TransactionParameters.init()
prms.xAmount = 1.23;
prms.xInvoice = "1234";
prms.xCommand = "cc:sale";
// ... other fields.

// Create the request object
let request = cardknoxUI.createRequest(withParameters: prms) as! PaymentTransactionRequestUI
// Create the parameters object
TransactionParameters *prms = [[TransactionParameters alloc] init];
prms.xAmount = 1.23;
prms.xInvoice = @"1234";
prms.xCommand = @"cc:sale";
// ... other fields.

// Create the request object
PaymentTransactionRequestUI * request = [cardknoxUI createRequestWithParameters:prms];

Check if the request object is in a valid state. If it is, call the method to show the UI. Otherwise, inspect the validation errors to see what is incorrect in the request object:

let request = cardknoxUI.createRequest(withParameters: prms) as! PaymentTransactionRequestUI

if(request.isValid){
  request.process()
}
else{
  let errors = request.validationErrors;
}
PaymentTransactionRequestUI * request = [cardknoxUI createRequestWithParameters:prms];

if([request IsValid]){
  [request process];
}
else{
  NSArray* errors = request.ValidationErrors;
}

Available user interfaces

The SDK’s user interface consists of two fullscreen parts - a manual entry screen and a card reader screen. Manual entry screen is also abbreviated as a “keyed” screen. The card reader screen is also abbreviated as a “swipe” screen.

Showing the SDK user interface via a Request object will either show one of the screens, or both. Which screen will be visible depends on the global SDK configuration state prior to showing the SDK user interface via a Request object.

Note that if the SDK is configured to allow access to both processing screens, one of them will be shown by default and both of them will have some kind of a visual way to navigate to the other one.

The following table shows available functions to control which screen will be visible & accessible:

The following mapping represents which screens will be available when the SDK shows its user interface:

The following mapping represents available Cardknox Transaction API commands on each user interface:

Pre processing options

Developer using the Out Of Scope integration to process using the VP3300 card reader can specify a per-request transaction timeout value. The SDK will start a transaction with the VP3300 reader, and timeout in the specified time frame if the card is not tapped, swiped or inserted in that same time frame.

Post processing options

After the out-of-scope function finishes with transaction processing, the SDK displays a popup containing a handful of information about the transaction.

SDK can be configured to auto close the user interface immediately after the transaction processing has completed; regardless if the transaction was approved or not.

In scope integration

In scope processing feature allows the developer to quickly process a payment and retrieve the response object.

First, create an “in scope” or “direct” manager kind of object. This object can create “request” objects that are capable of directly processing a transaction and returning back a “response” object.

let cardknoxDirect = CardknoxSDKDirect.create() as! CardknoxSDKDirect;
CardknoxSDKDirect* cardknoxDirect = [CardknoxSDKDirect create];

The developer is responsible for the CardknoxSDKDirect object instance. Once the object is no longer needed, the method named similar to destroy needs to be called. A good place to maintain the object are “appear” and “disappear” callbacks.

import SwiftUI
struct MyView: View {
  @State private var cardknoxDirect : CardknoxSDKDirect!;
  
  var body: some View{
    Label(title: {Text("Hello world")}, icon: {})
        .onAppear(perform:onAppearFunc)
        .onDisappear(perform:onDisappear)
  }
  
  func onAppearFunc(){
      CardknoxSDK.setPrincipalKey("Your xKey")
      CardknoxSDK.setxSoftwareName("Your app name", xSoftwareVersion: "1.0.0", xVersion: "4.5.9")
      cardknoxDirect = CardknoxSDKDirect.create() as! CardknoxSDKDirect;
  }
  
  func onDisappear(){
      if(cardknoxDirect != nil){
          cardknoxDirect.destroy();
      }
      cardknoxDirect = nil;
  }
}

To process directly, create a request object:

// Create the parameters object
let prms : TransactionParameters = TransactionParameters.init()
prms.xAmount = 1.23;
prms.xInvoice = "1234";
prms.xCommand = "cc:sale";
// ... other fields.

// Create the request object
let request = cardknoxDirect.createRequest(withParameters: prms) as! PaymentTransactionRequestDirect;

Check if the request object is in a valid state. If it is, call the method to process directly. Otherwise, inspect the validation errors to see what is incorrect in the request object:

let request = cardknoxDirect.createRequest(withParameters: prms) as! PaymentTransactionRequestDirect;

if(request.isValid){
    let response : PaymentTransactionResponse = request.process() as! PaymentTransactionResponse;
    let isSuccess = response.isSuccess();
    let errorMessage = response.errorMessage();
    let errorCode = response.xErrorCode();
    let refNum = response.xRefNum();
}
else{
    let errors = request.validationErrors;
}

Available commands

Custom UI integration

Custom UI integration is similar to the “out of scope” integration in a way that the exact same methods that the “out of scope” is using under the hood for controlling the card reader, are exposed via the SDK for the Developer to use.

The Developer provides the user interface and orchestrates the entire flow for obtaining the card data via the card reader by calling appropriate Custom UI functions at specific times.

Available commands

Any of the following credit card commands are available for Custom UI:

  • cc:save

  • cc:credit

  • cc:authonly

  • cc:sale

Reference: Transaction API

Custom UI flow

First, create a “custom ui” object to get access to all the Custom UI functions. Afterwards, subscribe to all the relevant callbacks for this integration path:

  • transaction result callback - to receive the “response” object after the SDK has processed a transaction

  • card reader event callback - to be notified about various events that take place between the application & the card reader

  • scanned bluetooth device callback - to be notified about every new scanned bluetooth device during the “scan for devices” process

  • scan completed callback - to be notified about all the scanned devices once the “scan for devices” process ends

Next step is to establish a connection between the app and the card reader device. Use one of the “connect” methods on the “custom ui” to initiate a connection; such as “connect with name” or “connect with UUID”.

Device name or the UUID can be obtained with the “scan for devices” flow. Initiate the “start scanning” function call, with or without a timeout.

The scanning process stops with a call to the “stop scanning” function or when the “start scanning” function times out.

After establishing a connection with the card reader by calling one of the “connect” methods and receiving a “connected” card reader event via the NSNotificationCenter subscription, call the “start transaction” function to make the card reader ready for a card.

The SDK will report a “transaction starting” card reader event via a callback followed by the “transaction started” event if the transaction with the card reader was successfully started, otherwise an “error” card reader event is reported back. At this point the card can be tapped, swiped or inserted into the card reader. The SDK will read the card information, process a transaction & deliver the results to the application via a callback.

If no card is tapped, swiped or inserted after the transaction started - a “timeout” card reader is reported back. The default timeout value is about 10 seconds. The developer can override this value via the “transaction parameters” object.

Versioning

Developers can call the “get version” API to obtain the SDK Semantic Versioning (SemVer source)

Logging

SDK verbose logging can be enabled or disabled with a function call:

FAQ

  1. As a Cardknox SDK user, I want to process without an internet connection. What will happen?

    • The SDK will return a PaymentTransactionResponse object with a special xErrorCode value -1

  2. As a Cardknox SDK user, I’ve encountered errors during transaction processing. What response can I expect?

    • The PaymentTransactionRequest object will encapsulate all relevant information in respective fields; for example the xErrorCode property will return a code from the Cardknox Transaction API documentation, the xErrorMessage and xError properties can be used for a descriptive error message while the xRefNum gives back a unique ref num to follow up with the customer support

Last updated