Payments SDK for iOS

The Payments SDK is a solution to ease the integration with the Alviere services.

Features

  • Cards Tokenization
  • Card Debit

Requirements

  • iOS 11.0+
  • Xcode 12+
  • Swift 5.3+

Installation

Swift Package Manager

1. Add the dependency to your project. Open your project and navigate to your project’s settings. Select the tab named Swift Packages and click on the add button + at the bottom left.

image

2. Enter the url of Payments SDK for the iOS repository (https://github.com/Alviere/alviere-payments-ios) in the text field and click Next.

image

3. On the next screen, select the SDK version and click Next.

image

4. Select the Payments package and click Finish.

image

5. Repeat the same process for AlCore SDK (https://github.com/Alviere/alviere-core-ios). The current version is compatible with AlCore SDK version 0.9.0 and up.

CocoaPods

1. Get the latest version of CocoaPods, if you haven’t already.

2. Create the Podfile by running the following command, if you don’t have one already.

pod init

3. Add this line to your Podfile.

pod 'Payments'

4. Run the following command to install the library. Also, run this to update to newer releases in the future.

pod install

Carthage

1. Get the latest version of Carthage, if you haven’t already.

2. Add the following entries in your Cartfile:

binary https://raw.githubusercontent.com/Alviere/alviere-core-ios/master/AlCore.json
binary https://raw.githubusercontent.com/Alviere/alviere-payments-ios/master/Payments.json

3. Run the following command to download the latest version of the SDK.

carthage update --use-xcframeworks

4. Follow the Manual instructions below to embed the SDK into your project.

Manual

1. Get the latest versions of Payments.xcframework and AlCore.xcframework and embed them into your application by dragging and dropping the files onto the Frameworks, Libraries and Embedded Content project section, as shown below.

image

2. Depending on the location of Payments.xcframework and AlCore.xcframework on the filesystem you may need to change the Framework Search Paths build setting to avoid the error: fatal error: ‘Payments/Payments.h’ file not found. For example, the Xcode project below have it set to FRAMEWORK_SEARCH_PATHS = $(PROJECT_DIR)/../ since the xcframeworks files are shared between them and are kept in the directory that also contains the project directories.

image

Usage

To initialize the Payments SDK for iOS, you need to set the Environment at the entry point of your application. For example, you can do this on your AppDelegate file on the application(_:,didFinishLaunchingWithOptions:) method, as shown below.

import AlCore

...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Setup Alviere SDK.
    if !AlCoreSDK.shared.setEnvironment(.sandbox) {
        print("Error initializing SDK.")
    }
    return true
}

After this setup, you just need to import the Payments SDK for iOS on the files where you want to use the features.

import Payments

Card Tokenization

Adopt the TokenizeCardDelegate protocol

This can be handled, for instance, by the view controller object that will present the UI.

extension ViewController : TokenizeCardDelegate

Implement the Delegate Methods

The TokenizeCardDelegate methods are the main communication back channel to your application for the Card Tokenization.

didSucceed

This delegate method is called when the user successfully linked their card with Alviere. Use this to upload and store the cardToken with your service for use with the Alviere API.

func didTokenizeCardWithSuccess(cardToken: String) {
    // Handle success, e.g. by storing cardToken with your service
    print("Successfully tokenized card with token \(cardToken)")
}

didHandleEvent

This delegate method is called when the user exited from the Payments SDK, when an error occurred, or when certain events in the Payments SDK flow have occurred. This enables your application to gain further insight into what is going on as the user goes through the Payments SDK flow. In case of an error you may want to display error related information to the user and have them try linking their card again.

func didHandleEvent(_ event: String, metadata: [String : String]?) {
    print("Received event: \(event)\nmetadata: \(metadata ?? [:])")
}

The event keys are defined on the Event enum and the metadata keys on Metadata enum.

Card Tokenization Presentation

Presenting the Card Tokenization is as simple as creating a new auth_token, using it to initialize AlPayments, and get/register the TokenizeCardViewController / TokenizeCardView instances. You can also use the card tokenization with your own UI.

Presenting Card Tokenization View Controller

From code

To instantiate TokenizeCardViewController from code, use createAddCardViewController to create a new auth_token and pass the TokenizeCardDelegate delegate instance. Optionally, you can also pass an extra data model, with an account id, and customization objects with the style and validation overrides you want to apply. You can either present the newly created view controller by pushing it, with show, or modally, with present.

let viewController = AlPayments.shared
    .createAddCardViewController(token: authToken,
                                 delegate: self,
                                 validation: validation,
                                 style: style)

self.navigationController?.show(viewController, sender: self)

When presenting modally, you still need to embed the view controller on a navigation controller and then present the navigation controller itself. If the TokenizeCardViewController has no navigation controller it will throw an error and crash your application.

let viewController = AlPayments.shared
    .createAddCardViewController(token: authToken,
                                 delegate: self,
                                 validation: validation,
                                 style: style)

let navigationController = UINavigationController(rootViewController: viewController)

self.present(navigationController, animated: true)

From Storyboard

To create an TokenizeCardViewController from a Storyboard or a xib you need to select your view controller. On the Custom Class section, set the Class as TokenizeCardViewController and enable the Inherit Module From Target checkbox. At this point, you only need to register your view controller with AlPayments, using the registerAddCardViewController, create a new auth_token and pass the TokenizeCardDelegate delegate instance. Optionally, you can also pass an extra data model, with an account id. Be sure that when presenting modally the TokenizeCardViewController needs to be embedded on a navigation controller or it will throw an error and crash your application.

image

If you present the view controller with a Segue you need to implement a prepare(for:, sender:) callback and then register the view controller.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    AlPayments.shared
        .registerAddCardViewController(token: authToken,
                                       viewController: segue.destination,
                                       delegate: self)
}

If you choose to instantiate the view controller by Storyboard ID and navigate manually, you just need to register the view controller.

let viewController = UIStoryboard(name: "Main", bundle: nil)
    .instantiateViewController(identifier: "TokenizeCardViewController") as! TokenizeCardViewController

AlPayments.shared
    .registerAddCardViewController(token: authToken,
                                   viewController: viewController,
                                   delegate: self)

self.navigationController?.show(viewController, sender: self)

Presenting Card Tokenization View Component

When using the Card Tokenization as a component, be advised that you will also have the task of handling the errors and navigation.

From Code

To instantiate TokenizeCardView from code, use createAddCardView where you will need to create a new auth_token and pass the TokenizeCardDelegate delegate instance. You also have the option to pass an extra data model, with an account id, and customization objects with the style and validation overrides you want to apply.

let view = AlPayments.shared
    .createAddCardView(token: authToken,
                       delegate: self,
                       validation: validation,
                       style: style)

From Storyboard

To create an TokenizeCardView from a Storyboard or a xib you need to select your view, and on the Custom Class section, set the Class as TokenizeCardView and enable the Inherit Module From Target checkbox.

image

Create an IBOutlet and register your view with AlPayments on the viewDidLoad method, using the registerAddCardView and, create a new auth_token and pass the TokenizeCardDelegate delegate instance. If you wish, you may also pass an extra data model, with an account id, and customization objects with the style and validation overrides you want to apply. Be advised that by this method you will miss the open event on the delegate.

@IBOutlet weak var tokenizeCardView: TokenizeCardView!

...

override func viewDidLoad() {
    super.viewDidLoad()

    AlPayments.shared
        .registerAddCardView(token: authToken,
                             view: tokenizeCardView,
                             delegate: self)
}

Card Tokenization Usage without UI

If you want to call the tokenization service directly, use createCardToken to create a new auth_token pass the CardTokenRequest model with the card data, and pass the TokenizeCardDelegate delegate instance. You also have the option to pass a customization object with the validation overrides you want to apply, for example for the zip/postal code field.

let model = CardTokenRequest( ... )

AlPayments.shared
    .tokenizeCard(token: authToken,
                  data: model,
                  delegate: self)

Card Debit

Adopt the CardDebitDelegate protocol

This can be handled by the view controller object that will present the UI component.

extension ViewController : CardDebitDelegate

Implement the Delegate Methods

The CardDebitDelegate methods are the main communication back channels to your application for the Card Debit.

didAcceptCardDebit

This delegate method is called when the card debit is successful.

func didAcceptCardDebit() {
    // Handle success
    print("Payment checkout successful")
}

didHandleEvent

This delegate method is called when certain events in the Payments SDK flow have occurred. This enables your application to gain further insight into what is going on as the user goes through the Payments SDK flow. In case of an error, you may want to display error related information to the user.

func didHandleEvent(_ event: String, metadata: [String : String]?) {
    print("Received event: \(event)\nmetadata: \(metadata ?? [:])")
}

The event keys are defined on the Event enum and the metadata keys on Metadata enum.

Card Debit Presentation

Starting the Payments SDK for iOS is as simple as creating a new auth_token, using it to initialize AlPayments, get/register a CardDebitButton instance, and provide a CardDebitRequest model. You can also use the payment checkout with your own UI.

Presenting Card Debit Button

From Code

To instantiate CardDebitButton from code, use createCardDebitButton where you will need to create a new auth_token and pass the CardDebitDelegate delegate instance. You also have the option to pass a customization object with the style overrides you want to apply.

let view = AlPayments.shared
    .createCardDebitButton(token: self.authToken,
                           delegate: self,
                           style: style)

After this, set the CardDebitRequest model with the data to proceed with the debit. You can do this on your viewDidLoad method, for instance.

@IBOutlet weak var cardDebitButton: CardDebitButton!

...

override func viewDidLoad() {
    super.viewDidLoad()

    let model = CardDebitRequest( ... )

    self.cardDebitButton.setRequestData(model)
}

From Storyboard

To create a CardDebitButton from a Storyboard or a xib, you need to select your view, and on the Custom Class section, set the Class as CardDebitButton and enable the Inherit Module From Target checkbox.

image

Create an IBOutlet and register your view with AlPayments on the viewDidLoad method using the registerCardDebitButton, create a new auth_token and pass the CardDebitDelegate delegate instance. You also need to set the CardDebitRequest model with the data to proceed with the checkout.

@IBOutlet weak var cardDebitButton: CardDebitButton!

...

override func viewDidLoad() {
    super.viewDidLoad()

    AlPayments.shared
        .registerCardDebitButton(token: authToken,
                                 view: cardDebitButton,
                                 delegate: self)

    let model = CardDebitRequest( ... )

    self.cardDebitButton.setRequestData(model)
}

Card Debit Usage without UI

If you want to call the card debit service directly, use cardDebit to create a new auth_token pass the CardDebitRequest model with the card data, and pass the CardDebitDelegate delegate instance.

let model = CardDebitRequest( ... )

AlPayments.shared
    .cardDebit(token: authToken,
               data: model,
               delegate: self)

Fraud Prevention Service

The Payments SDK has a built-in fraud prevention service. This service is automatically activated when you do a Card Tokenization. If you already have done a Card Tokenization and want to activate the service on the next app run you just need to set the cardToken on the service as the user id. For example, you can do this on your AppDelegate file on the application(_:,didFinishLaunchingWithOptions:) method, as shown below. When you use the Payments SDK for iOS and Accounts SDK for iOS in conjunction pay attention that you should set the user accountUuid on the service instead of the cardToken.

import AlCore

...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Setup Alviere SDK.
    if !AlCoreSDK.shared.setEnvironment(.sandbox) {
        print("Error initializing SDK.")
    }

    // Start fraud prevention service.
    AlCoreSDK.shared.setUserId(cardToken)
    return true
}

To fully enable the service you need to do a small setup by adding the add the LSApplicationQueriesSchemes array in your Info.plist file. Right-click somewhere outside the table and select Add Row. Now add the entries like below.

image

Or if you prefer to do this step with code, right-click on Info.plist and select Open As > Source Code. Add the lines below somewhere inside the <dict> </dict>.

<!-- Fraud prevention setup to be included in Info.plist -->
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>cydia</string>
</array>

Customization

The Payments SDK for iOS provides a set of UI styling and field validation customizations to allow you to adjust the provided UI to fit your needs by setting a style model. To customize the UI, start from the default style and make the changes; you can also select the card brands that you wish to support on validations. The default includes all brands. You can check the supported brands on CardBrand enum.

var style = TokenizeCardStyle.getDefaultStyle()
style.backgroundColor = UIColor.white
...

Styling

Below are the styling options provided that are used to compose style models like TokenizeCardStyle.

Class Attribute Description
ViewStyle backgroundColor UIColor that affects the background color of UIView
  darkBackgroundColor UIColor that affects the background color of UIView in dark mode
TextStyle color UIColor that affects the text color of UILabel
  darkColor UIColor that affects the text color of UILabel in dark mode
  font UIFont that affects the text font of UILabel
ButtonStyle backgroundColor UIColor that affects the background color of UIButton
  darkBackgroundColor UIColor that affects the background color of UIButton in dark mode
  titleStyle TextStyle that affects the text font and color of UIButton
  cornerRadius CGFloat that controls the corner radius of UIButton
  margins UIEdgeInsets that controls the margins of UIButton
TextFieldStyle backgroundColor UIColor that affects the background color of UITextField
  darkBackgroundColor UIColor that affects the background color of UITextField in dark mode
  textStyle TextStyle that affects the text font and color of UITextField text
  placeholderStyle TextStyle that affects the text font and color of UITextField placeholder
  keyboardType UIKeyboardType for field
TokenizeCardFieldStyle backgroundColor UIColor that affects the background color of a field
  darkBackgroundColor UIColor that affects the background color of a field in dark mode
  textFieldStyle TextFieldStyle that affects the style of UITextField
  errorLabelStyle TextStyle that affects the text font and color of error UILabel

Validation

Below are the validation customizations provided that you can use to change some field validations to fit your needs. They are used to compose validation models like TokenizeCardValidation.

Class Attribute Description
CardBrand enum of supported card brands
TextValidation regex validation regex
  minimumCharacters minimum allowed characters
  maximumCharacters maximum allowed characters
  isRequired sets the field as required

Text and Localization

The Payments SDK for iOS allows you to customize the UI text. To do so, you will need to redefine the localization key that you want to change on your Localizable.strings file. The next section details a list of the current localization keys. Currently, the SDK only provides english localization.

Localization Keys

Key English Value
alviere_sdk_payments_add_card_title Add Card
alviere_sdk_payments_add_card_number_placeholder Number
alviere_sdk_payments_add_card_expiration_date_placeholder Expiration Date
alviere_sdk_payments_add_card_cvc_placeholder CVC
alviere_sdk_payments_add_card_cvv_placeholder CVV
alviere_sdk_payments_add_card_cardholder_name_placeholder Cardholder Name
alviere_sdk_payments_add_card_zip_code_placeholder Zip Code
alviere_sdk_payments_add_card_add_title Add
alviere_sdk_payments_add_card_add_error_required_field Required
alviere_sdk_payments_add_card_add_error_invalid_field Invalid
alviere_sdk_payments_add_card_add_error_invalid_card Invalid or unsupported card
alviere_sdk_payments_payment_card_debit_checkout_title Checkout
alviere_sdk_vo_payments_error_on_field Error on field %@. %@.\n
alviere_sdk_loading_title Loading
alviere_sdk_error_title Error
alviere_sdk_error_try_again Try Again
alviere_sdk_error_generic An error has occurred
alviere_sdk_vo_loading_done Finished loading