Skip to content

DagAgren/vgs-collect-ios

 
 

Repository files navigation

CircleCI UT license Platform swift Cocoapods Compatible

VGS Collect iOS SDK

VGS Collect - is a product suite that allows customers to collect information securely without possession of it. VGSCollect iOS SDK allows you to securely collect data from your users via forms without having to have that data pass through your systems. The form fields behave like traditional input fields while securing access to the unsecured data.

Table of contents

VGS Collect iOS SDK State VGS Collect iOS SDK Response

Before you start

You should have your organization registered at VGS Dashboard. Sandbox vault will be pre-created for you. You should use your <vaultId> to start collecting data. Follow integration guide below.

Integration

VGSCollectSDK is available through CocoaPods and Carthage.

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate VGSCollectSDK into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'VGSCollectSDK'

Carthage

VGCollectSDK is also available through Carthage. Add the following line to your Cartfile:

github "verygoodsecurity/vgs-collect-ios"

then run:

carthage update --platform iOS

Note that VGSCollectSDK includes CardIO as dependency for scanning card numbers. You should also link it to your project. Follow the Carthage instructions

Usage

Import SDK into your file

import VGSCollectSDK

Create VGSCollect instance and VGS UI Elements

Use your <vaultId> to initialize VGSCollect instance. You can get it in your organisation dashboard.

Code example

Here's an example In Action
Customize VGSTextFields...
/// Initialize VGSCollect instance
var vgsCollect = VGSCollect(id: "vauiltId", environment: .sandbox)

/// VGS UI Elements
var cardNumberField = VGSCardTextField()
var cardHolderNameField = VGSTextField()
var expCardDateField = VGSTextField()
var cvcField = VGSTextField()

/// Native UI Elements
@IBOutlet weak var stackView: UIStackView!

override func viewDidLoad() {
    super.viewDidLoad()

    /// Create card number field configuration
    let cardConfiguration = VGSConfiguration(collector: vgsCollect,
                                         fieldName: "card_number")
    cardConfiguration.type = .cardNumber
    cardConfiguration.isRequiredValidOnly = true

    /// Setup configuration to card number field
    cardNumberField.configuration = cardConfiguration
    cardNumberField.placeholder = "Card Number"
    stackView.addArrangedSubview(cardNumberField)

    /// Setup next textfields...
}
...
... observe filed states
override func viewDidLoad() {
    super.viewDidLoad()
	
    ...  
	
    /// Observing text fields
    vgsCollect.observeStates = { textFields in

        textFields.forEach({ textField in
            print(textdField.state.description)
            if textdField.state.isValid {
                textField.borderColor = .grey
            } else {
                textField.borderColor = .red
            }

            /// CardState is available for VGSCardTextField
            if let cardState = textField.state as? CardState {
                print(cardState.bin)
                print(cardState.last4)
                print(cardState.brand.stringValue)
            }
        })
    }
}
... send data to your Vault
// ...

// MARK: - Send data    
func sendData() {

    /// handle fields validation before send data
    guard cardNumberField.state.isValid else {
	print("cardNumberField input is not valid")
    }

    /// extra information will be sent together with all sensitive card information
    var extraData = [String: Any]()
    extraData["customKey"] = "Custom Value"

    /// send data to your Vault
    vgsCollect.sendData(path: "/post", extraData: extraData) { [weak self](response) in
      switch response {
        case .success(let code, let data, let response):
          // parse data
        case .failure(let code, let data, let response, let error):
          // handle failed request
          switch code {
            // handle error codes
          }
      }
    }
}

VGSCardTextField automatically detects card provider and display card brand icon in the input field.

Scan Credit Card Data

VGSCollect provide secure card.io integration for collecting and setting scanned data into VGSTextFields. To use card.io with VGSCollectSDK you should add CardIO module alongside with core VGSCollectSDK module into your App Podfile:

pod 'VGSCollectSDK'
pod 'VGSCollectSDK/CardIO'

Code Example

Here's an example In Action
Setup VGSCardIOScanController...
class ViewController: UIViewController {
	 
    var vgsCollect = VGSCollect(id: "vauiltId", environment: .sandbox)

    /// Init VGSCardIOScanController
    var scanController = VGSCardIOScanController()

    /// Init VGSTextFields...

    override func viewDidLoad() {
        super.viewDidLoad()

        /// set VGSCardIOScanDelegate
        canController.delegate = self
    }

    /// Present scan controller 
    func scanData() {
        scanController.presentCardScanner(on: self,
				animated: true,
			      completion: nil)
    }

    // MARK: - Send data  
    func sendData() {
        /// Send data from VGSTextFields to your Vault
        vgsCollect.sendData{...}
    }
}
...
... handle VGSCardIOScanControllerDelegate
// ...

/// Implement VGSCardIOScanControllerDelegate methods
extension ViewController: VGSCardIOScanControllerDelegate {

    ///Asks VGSTextField where scanned data with type need to be set.
    func textFieldForScannedData(type: CradIODataType) -> VGSTextField? {
	switch type {
	case .expirationDate:
	    return expCardDateField
	case .cvc:
	    return cvcField
	case .cardNumber:
	    return cardNumberField
	default:
	    return nil
	}
    }

    /// When user press Done button on CardIO screen
    func userDidFinishScan() {
	scanController.dismissCardScanner(animated: true, completion: { [weak self] in
	    /// self?.sendData()
	})
    }
}

Handle VGSCardIOScanControllerDelegate functions. To setup scanned data into specific VGSTextField implement textFieldForScannedData: . If scanned data is valid it will be set in your VGSTextField automatically after user confirmation. Check CradIODataType to get available scand data types.

Don't forget to add NSCameraUsageDescription key and description into your App Info.plist.

Upload Files

You can add a file uploading functionality to your application with VGSFilePickerController.

Code Example

Setup VGSFilePickerController...
class FilePickerViewController: UIViewController, VGSFilePickerControllerDelegate {

  var vgsCollect = VGSCollect(id: "vailtId", environment: .sandbox)
  
  /// Create strong referrence of VGSFilePickerController
  var pickerController: VGSFilePickerController?

  override func viewDidLoad() {
      super.viewDidLoad()

      /// create picker configuration
      let filePickerConfig = VGSFilePickerConfiguration(collector: vgsCollect,
      							fieldName: "secret_doc",
						       fileSource: .photoLibrary)

      /// init picket controller with configuration
      pickerController = VGSFilePickerController(configuration: filePickerConfig)

      /// handle picker delegates
      pickerController?.delegate = self
  }

  /// Present picker controller
  func presentFilePicker() {
      pickerController?.presentFilePicker(on: self, animated: true, completion: nil)
  }
}
...
... handle VGSFilePickerControllerDelegate In Action
// ...  

// MARK: - VGSFilePickerControllerDelegate
/// Check file info, selected by user
func userDidPickFileWithInfo(_ info: VGSFileInfo) {
	let fileInfo = """
		    File info:
		    - fileExtension: \(info.fileExtension ?? "unknown")
		    - size: \(info.size)
		    - sizeUnits: \(info.sizeUnits ?? "unknown")
		    """
	print(fileInfo)
	pickerController?.dismissFilePicker(animated: true,
					  completion: { [weak self] in
					  
		self?.sendFile()
	})
}

// Handle cancel file selection
func userDidSCancelFilePicking() {
	pickerController?.dismissFilePicker(animated: true)
}

// Handle errors on picking the file
func filePickingFailedWithError(_ error: VGSError) {
	pickerController?.dismissFilePicker(animated: true)
}
... send file to your Vault
// ...

// MARK: - Send File	
/// Send file and extra data
func sendFile() {

	/// add extra data to send request	
	let extraData = ["document_holder": "Joe B"]

  /// send file to your Vault
  vgsCollect.sendFile(path: "/post", extraData: extraData) { [weak self](response) in
    switch response {
      case .success(let code, let data, let response):
        /// remove file from VGSCollect storage
        self?.vgsCollect.cleanFiles()
      case .failure(let code, let data, let response, let error):
        // handle failed request
        switch code {
          // handle error codes
        }
    }
  }
}

Use vgsCollect.cleanFiles() to unassign file from associated VGSCollect instance whenever you need.

Demo Application

Demo application for collecting card data on iOS is here.

Documentation

Releases

To follow VGSCollectSDK updates and changes check the releases page.

Dependencies

  • iOS 10+
  • Swift 5
  • 3rd party libraries:
    • CardIO(optional)

License

VGSCollect iOS SDK is released under the MIT license. See LICENSE for details.

Packages

 
 
 

Languages

  • Swift 98.2%
  • Ruby 1.5%
  • Objective-C 0.3%