# Masterpass Checkout iOS SDK v2.0
source: https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/previous-releases/masterpass-checkout-ios-sdk-v2/index.md

**This page contains details of the 2.0 release (2017 R7) of the SDK. For details of the latest release, see [here](https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/previous-releases/masterpass-checkout-ios-sdk-v25/index.md)**.

## Overview {#overview}

With the Masterpass iOS Checkout SDK, you can quickly and easily integrate secure and native Masterpass checkout services into your iOS app, enabling consumers to pay using their Masterpass wallets.

You can integrate Masterpass for the "[Standard Checkout](https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/backend-integration/#standard-checkout)" and "[Express Checkout](https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/web-integration/#express-checkout)" flows. With Standard Checkout, the your [checkout screen](https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/previous-releases/masterpass-checkout-ios-sdk-v2/index.md#sample-screen) will contain the Masterpass Button, which redirects consumers to the Masterpass web checkout experience (in Safari) where they are to sign in and choose their payment method. With Express Checkout, consumers have the option to pair their payment details wallets with you in order to streamline their checkout experiences.

**Note: Express Checkout is not supported in the US and Canada. Please contact your regional representative for more information.**

For more information on checkout experiences, see [Masterpass Checkout Experiences](https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/masterpass-checkout-experiences/index.md).

### Prerequisites {#prerequisites}

Download the SDK zip files below.

| Environment |                                                                      ZIP File                                                                       |
|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| Sandbox     | [MCCMerchant_Sandbox.zip](https://static.developer.mastercard.com/content/masterpass-merchant-integration-v7/uploads/mccmerchant-sandbox.zip)       |
| Production  | [MCCMerchant_Production.zip](https://static.developer.mastercard.com/content/masterpass-merchant-integration-v7/uploads/mccmerchant-production.zip) |

To integrate with the SDK, you must provide:  

* A custom [URL Scheme](https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Inter-AppCommunication/Inter-AppCommunication.html#//apple_ref/doc/uid/TP40007072-CH6-SW1) for the Standard Checkout app-to-web communication.  
  Merchant-specific **CHECKOUTID** and **CARTID** parameters during Standard Checkout.  
  Merchant-specific **CHECKOUTID** and **USERID** parameters during Express Checkout

**NOTE:** During the Masterpass [merchant onboarding process](https://developer.mastercard.com/masterpass-merchant-onboarding/documentation/), you must configure the Masterpass Merchant Portal with the related **CHECKOUTID** and **URL Scheme** so that the URL callback method (from Masterpass site to merchant app) can be triggered correctly.

Before being enabled for Express Checkout, you must pass the Masterpass security vetting specifications, see [Masterpass Checkout Experiences](https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/masterpass-checkout-experiences/index.md).

#### Sample Screen {#sample-screen}

This screenshot shows the Masterpass Button added to the checkout view of an example merchant iOS app.

![alt text](https://static.developer.mastercard.com/content/masterpass-merchant-integration-v7/documentation/images/mpass-scr-merchant-ios-screenshot.png)

### Integration {#integration}

This integration tutorial goes through the typical steps involved to demonstrate how you can add Masterpass to your iOS merchant app.

#### 1. Add the SDK to your Application {#1-add-the-sdk-to-your-application}

In your Xcode project, select your target and add **MCCMerchant.framework** to:  

* General tab:**Linked Frameworks and Libraries** and **Embedded Binaries**
* Build Phases tab: **Link Binary with Libraries**

You can drag the framework file into each area or use the + buttons, as shown below.

![alt text](https://static.developer.mastercard.com/content/masterpass-merchant-integration-v7/documentation/images/mpass-scr-xcode-adding-framework.png)

Xcode automatically adds the framework to **Embed Frameworks** , in the Build Phases tab. Ensure that **Code Sign On Copy** is checked for the framework.

#### 2. Initialize the SDK {#2-initialize-the-sdk}

To initialize the SDK, you must provide an**MCCConfiguration** object to the SDK initializing class method, which returns a singleton instance of the SDK.
* Swift

```Swift
// Create SDK configuration object

 let configuration: MCCConfiguration = MCCConfiguration()
 configuration.enableAnalytics = true
 configuration.merchantUrlScheme = "MyMerchant://"
 configuration.locale = NSLocale.current
 // Start SDK initialization

 MCCMerchant.initializeSDK( with: configuration) { (status:[AnyHashable : Any], error: Error?) -> Void in

     let statusDictionary = status as? [String:AnyObject]
     let statusCode: Int = (statusDictionary?[kInitializeStateKey]?.intValue)!
     switch (MCCInitializationState(rawValue: statusCode)!) {

     case .started:
         //Started
         //Here you can perform other custom UI tasks like showing an activity indicator.               
         break

     case .completed:
         //Complete
         //Here you can hide the activity indicator and add call the getMPButton or create your own button
         self.getMasterPassButton()
         break

     case .fail:
         //Error
         //On error, reset any custom UI / animations (e.g. hide the activity indicator) and if the MPButton was previously shown, hide it.
         //Inform the user an error has occurred.
         if (self.masterPassButton != nil) {
             self.masterPassButton?.removeFromSuperview()
         }
         break
     }
}
```

#### 3. Implement the Standard Checkout {#3-implement-the-standard-checkout}

To start the Standard Checkout process, there is typically a checkout view controller sub-class (such as a table view) that shows the items being purchased and other transaction details. Add the Masterpass Button to this checkout view.

##### 3a. Set Up your Checkout View Controller with MCCMasterpassButton {#3a-set-up-your-checkout-view-controller-with-mccmasterpassbutton}

Add the **MCCMasterpassButton** object to your view controller subclass, which provides the Masterpass Button to the consumer.
* Swift

```Swift
//Checkout UI Page
class CheckOutVC: UIViewController {
    var masterPassButton : MCCMasterpassButton?      
    self.masterPassButton = self.getMasterPassButton()
    // Other custom implementation for your view controller ...
}
```

##### 3b. Display the Masterpass Button {#3b-display-the-masterpass-button}

To display the Masterpass Button, the **getMasterPassButton()** function wraps the call to the SDK.
* Swift

```Swift
// MARK: Buy with Masterpass button
func getMasterPassButton() -> MCCMasterpassButton? {
    let masterpassButton = MCCMerchant.getMasterPassButton(self)
    return masterpassButton
}
```

##### 3c. Declare the Merchant Delegate {#3c-declare-the-merchant-delegate}

Add the **MCCMerchantDelegate** object to your checkout class (MerchantCheckoutManager) declaration line.
* Swift

```Swift
class MerchantCheckoutManager:NSObject, MCCMerchantDelegate {

    //Checkout Logic ...
}
```

##### 3d. Implement the Merchant Delegate Method {#3d-implement-the-merchant-delegate-method}

Add the delegate method, providing the **CHECKOUTID** and **CARTID** variables for your merchant app.
* Swift

```Swift
//MerchantCheckoutManager.swift

    // MARK: Build up your checkout request here
    func didGetCheckoutRequest(_ completionBlock: ((MCCCheckoutRequest) -> Bool)?) {

       let transactionRequest = MCCCheckoutRequest()

       //check merchant on-boarding process for checkoutId & cartID
       transactionRequest.checkoutId = {ADD_YOUR_CHECKOUTID}
       transactionRequest.cartId = {ADD_YOUR_CARTID}

       //amount and currency
       var amt = NSDecimalNumber(string:"75")        
       let amount:MCCAmount = MCCAmount()
       amount.total = amt
       amount.currencyCode = "USD"
       transactionRequest.amount = amount

       //network type
       var allowedNetworkTypesSet = Set<MCCCardType>()
       allowedNetworkTypesSet.insert(MCCCardType(type: MCCCard.MASTER)!);
       transactionRequest.allowedCardTypes = allowedNetworkTypesSet

       //cryptogram type
       transactionRequest.cryptogramType =  MCCCryptogram(type: MCCCryptogramType.UCAF)

       //shipping required
       transactionRequest.isShippingRequired = true

       completionBlock(transactionRequest)
    }

    // MARK: delegate method to handle the checkout error
    func didReceiveCheckoutError(_ error: Error) {
        let errorObject = error as NSError
        if (errorObject.domain == MCCMerchantSDKTransactionErrorDomain) {
            //Do something with error
            self.showErrorDialogue(error.localizedDescription, action: nil)
        } else {
            self.showError(errorObject)
        }
    }

    //MARK: delegate method to handle the checkout response
    func didFinishCheckout(_ checkoutResponse: MCCCheckoutResponse) {
        if (responseInfo != nil) {
            let webCheckoutType : MCCResponseType = responseInfo!.responseType
            if (webCheckoutType == .webCheckout){
                //do something
            }
        }
    }
```

##### 3e. Perform the Standard Checkout using Safari {#3e-perform-the-standard-checkout-using-safari}

Clicking the Masterpass button will trigger the Safari view controller to pass the transaction request data to the Masterpass site.

##### 3f. Transaction Completion {#3f-transaction-completion}

When the wallet app returns the transaction response data (payment information), the merchant app will be brought to the foreground using the merchant custom URL Scheme. This event needs to be handled in the ***application:open url:sourceApplication*** of the app delegate for the merchant app by invoking the **handleMasterpassResponse** method of the SDK.
* Swift

```Swift
//AppDelegate.swift
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return MCCMerchant.handleMasterpassResponse(url.absoluteString, delegate: self)
}
```

**NOTE:** The URL callback method uses the **CHECKOUTID** and **URL Scheme** configured in the Masterpass Merchant Portal during onboarding.

As shown in section 3d, the **didFinishCheckout** delegate method will be triggered when the correct response is generated. You need to handle the response correctly inside this delegate method.
* Swift

```Swift
//MARK: delegate method to handle the checkout response here
func didFinishCheckout(_ checkoutResponse: MCCCheckoutResponse) {
    if (responseInfo != nil) {
        let webCheckoutType : MCCResponseType = responseInfo!.responseType
        if (webCheckoutType == .webCheckout){
            //do something
        }
    }
}
```

#### 4. Implement the Express Checkout {#4-implement-the-express-checkout}

To enable the Express Checkout experience, the SDK is used to retrieve the **pairingTransactionId** with class method **pairingwithCheckout(isCheckout, merchantDelegate)** provided. The delegate methods need to be slightly altered based on the request.

##### 4a. Set Up Button with API {#4a-set-up-button-with-api}

The **pairingWithCheckoutClicked** function wraps the call to the Express Checkout API.
* Swift

```Swift
@IBAction func pairingWithCheckoutClicked(_ sender: Any) {
     //MARK: trigger pairing with/without checkout
    MCCMerchant.pairing(withCheckout: _isCheckout, merchantDelegate: MerchantCheckoutManager.sharedInstance)
}
```

##### 4b. Pairing with or without Checkout {#4b-pairing-with-or-without-checkout}

Add the delegate method, providing the **USERID** and **CHECKOUTID** variables.
* Swift

```Swift
//MerchantCheckoutManager.swift
// MARK: Build up your checkout request here
func didGetCheckoutRequest(_ completionBlock: ((MCCCheckoutRequest) -> Bool)?) {

   let transactionRequest = MCCCheckoutRequest()
   transactionRequest.userId = {ADD_YOUR_USERID}

   if (self.isPairingOnly) {
        //Pairing only request needs userId & checkoutID
        transactionRequest.checkoutId = {ADD_YOUR_CHECKOUTID}
        return transactionRequest
    }
   //... follow the same logic as web checkout

   completionBlock(transactionRequest)
}

//MARK: delegate method to handle the checkout response here
func didFinishCheckout(_ checkoutResponse: MCCCheckoutResponse) {
    if (responseInfo != nil) {
        let webCheckoutType : MCCResponseType = responseInfo!.responseType
        if (webCheckoutType == .webCheckout){
            //analyze response
        } else {
            //add pairing response
            if((responseInfo?.pairingTransactionID) != nil){
                //retrieve pairingTransactionID
            }

        }
    }
}
```

##### 4c. Complete the Implementation {#4c-complete-the-implementation}

To complete the Express Checkout implementation, see [Express Checkout](https://developer.mastercard.com/masterpass-merchant-integration-v7/documentation/web-integration/#express-checkout).

### Onboarding {#onboarding}

For information on merchant onboarding, see [Merchant Onboarding for Masterpass Checkout](https://developer.mastercard.com/masterpass-merchant-onboarding/documentation/). Make sure your custom URL scheme is configured properly within the onboarding process so Safari will be able to trigger your application when the transaction is done on the web.

### Testing {#testing}

To test the integration:  

1. Install your merchant app and launch it to initialize the SDK.
2. Depending on which checkout experience you want to test, use a test consumer account that is either:

* "Unpaired," for Standard Checkout
* "Paired," for Express Checkout

3. Start the checkout process by navigating to your checkout view controller and then click the Masterpass Button to start a transaction.
4. If the user is using an unpaired consumer account, the app should use the Safari view controller to access the Masterpass site. Follow the screens and prompts to provide the required information.
5. Masterpass returns the payment information to the merchant app.
6. Complete the transaction on the merchant side by making the required service calls.
