This guide helps you get started with the Checkout SDK on iOS.

Prerequisites

  • A ClientId and an API key – if you don’t have these, contact Sales to get access to the Mangopay Dashboard
  • A User and their associated Wallet to complete the pay-in
  • A card to register or payment method setup (see Testing - Payment methods for testing information)

For iOS:

  • iOS 13+
  • Xcode 12.2
  • Swift 5.3+

Best practice – Check out our example app and demo

To support you with your integration, be sure to make use of our example app on GitHub.

Installation

You can install the Mangopay Checkout SDK using SPM or Cocoapods.

  • Open your Xcode project and go to File > Swift Packages > Add Package Dependency
  • In the prompted dialog, enter the repository URL https://github.com/Mangopay/mangopay-ios-sdk
  • Select the checkout-ios-sdk package by checking the corresponding checkbox
  • Follow the on-screen instructions to complete the installation

Cocoapods

Open your podfile and add:

pod 'MangopayCheckoutSDK’

Add these sources above your podfile:

source 'https://github.com/CocoaPods/Specs.git'
source 'https://gitlab.com/mangopay/dev/checkout-ios-sdk'

Initialization

Initialize the SDK with your ClientId and select your environment (Sandbox or Production).

Note – Initialize once per app instance

The initialization should only be done once for an instance of the application.

We recommend putting this inside the AppDelegate class.


        MangopayCheckoutSDK.initialize(
            clientId: <client_id>,
            profilingMerchantId: <profilingMerchant_id>,
            checkoutReference: <checkoutReference>,
            environment: <env>
        )

Initialization parameters

PropertyTypeDescription
clientIdStringThe unique identifier associated with the Mangopay API key, giving access to the Mangopay API.
profilingMerchantIdStringThe unique identifier associated with your fraud protection package. Contact Mangopay to obtain this value.
checkoutReferenceStringAn identifier for your checkout session.
environmentEnvironment

The Mangopay environment.
Allowed values: SANDBOX, PRODUCTION
Default values: SANDBOX

Payment sheet configuration

To configure the Checkout SDK’s payment sheet:

1

Create a payment sheet instance in your ViewController

var checkout: MGPPaymentSheet!
2

Configure paymentSheet with paymentMethodOptions

let paymentMethodOptions = PaymentMethodOptions(
    cardOptions: cardOptions,
    applePayOptions: applePayOptions,
    paypalOptions: paypalOptions
)
3

Present the payment sheet

checkout.present(in: self)

Handling redirection

Warning – Use Mangopay Checkout domain as return URL

When making the pay-in request from your backend, use the Mangopay Checkout URL as the SecureModeReturnURL or ReturnURL (depending on the payment method):

http://checkout.mangopay.com

The user must be returned to this URL after redirection.

Some payment methods (card, Google Pay, PayPal) require or may require the user to be redirected to authorize or complete a transaction.

The Checkout SDK allows you to manage the entire payment flow seamlessly while retaining control over transaction logic in your backend. Once a payment method is selected and payment details are provided, use the onCreatePayment function to request the transaction from your backend.

Subsequently, and when necessary for the transaction type, the Checkout SDK seamlessly manages additional redirect actions for 3DS authorization or otherwise validating the payment.

To manage transaction redirects effectively with the SDK:

1

Define onCreatePayment

In your paymentMethodOptions configurations, define an onCreatePayment attribute as a function.

2

Within your function:

  • Request a transaction from your server and subsequently, Mangopay.
  • Return the unaltered transaction response object to the SDK.
3

The SDK:

  • Redirects the user to the payment authentication page when necessary.
  • Manages payment provider redirects back to the SDK.
  • Triggers the onPaymentComplete event with the ID and status of the transaction.
  • Confirms the redirect result on your server by invoking the corresponding GET API of the transaction.
  • Presents the payment result to the user.

Redirection example

            callback: CallBack(
                 onCreatePayment: { paymentMethod, attemptRef in
                     // 1. implement server-side call to request a transaction (with the attempt reference).
                                     // 2. return the card transaction object.
                                     return <Card_Transaction_Object>
                 }
             )    

Creating payment handler callbacks

    let callback = CallBack(
         onPaymentMethodSelected: { paymentMethod in
         },
         onTokenizationCompleted: { tokenizedData in
         
         },
         onCreateCardRegistration: { cardInfo in
         },
         onPaymentCompleted: { attemptReference, result in
         },
         onCreatePayment: { paymentMethod, attemptReference in
           switch paymentMethod {
             case .card(_):
             //
             case .payPal:
             default: return nil
             }
             },
        onCancel: {
         },
         onError: { error in
         }
     )

Callback parameters

PropertyTypeDescription
onPaymentMethodSelected((PaymentMethod) -> Void)Triggered when a payment method has been selected.
onTokenizationCompleted((TokenizedCardData) -> Void)Triggered when a card tokenization is completed and a CardId is returned.
onCreateCardRegistration((MGPCardInfo) async -> MGPCardRegistration?)Triggered only when the user selects card payment. This callback gives you control over making the card registration optional during the session.
onPaymentCompleted((PaymentMethod, String?) async -> Payable?)Triggered when the transaction is completed, whatever the outcome (whether successful or failed).
onCancelled() -> Void)?Called when the payment sheet is closed.
onErrorTriggered when an internal Checkout SDK error has occurred.

Presenting the payment result

    
Checkout Screen  -> Payment sheet -> Confirmation screen 

checkout = MGPPaymentSheet.create(
           paymentMethodOptions: paymentConfig,
           branding: PaymentFormStyle(),
           callback: CallBack(
               onTokenizationCompleted: { cardRegistration in
                                    **//dismiss the payment sheet**
                                     self.checkout.teardown()
                                    **//present the confirmation screen**
               },
               onError: { error in
               },
               onSheetDismissed: {
               }
           )
       )

       checkout.present(in: self)

Configuring card payments

let cardOptions = MGPCardOptions(supportedCardBrands: [.mastercard, .visa, .discover])
PropertyTypeDescription
supportedCardSchemesArray<[CardType]>The card brands to be shown.
cardRegistrationCardRegistration?You can provide CardRegistration optionally from configuration or provide it from callbacks.

Card tokenization

In the options for the card payment method, create a function to handle creation of Card Registration event handler in the payment methods object:

  • Your onCreateCardRegistration function calls your server, and passes it the card brand of the user.
  • Your server makes a request to Create a Card Registration.
  • In response, your server receives a Card Registration object.
  • In your onCreateCardRegistration function, return the unmodified Card Registration object to the SDK.
  • The SDK tokenizes the card and updates the Card Registration object to create the CardId which is used for payment.

tokenizationComplete output

REST
{
  "Id": "cardreg_m_01HQ0J6GB3JFZ1NC5EGCJBE4PB",
  "Tag": null,
  "CreationDate": 1708342329,
  "UserId": "user_m_01HP6ZG0XXZ89V34GRZEY9HQCE",
  "AccessKey": "1X0m87dmM2LiwFgxPLBJ",
  "PreregistrationData": "YkgVxL1yNY4ZOfKtqEew_Zj34Eg4_H3r-UyvrLWB_MHYF1OqkWAtDMwDMZ0pSZfliRF4hvSrtJCvT7-9XAi0Xsj7Q1OS-vT4lpHzEztZoLs",
  "RegistrationData": "data=iN_eoipU7i2AEuTss7wuoPRZYTuNVHlTvhc4dEXHczhSWquUg8N2vrbXU91rCDepo0Fw6rcqxRBK8KMWk8xhHGOBEuIr9_d-Xo64K6cr5w-lY2yXbTUOs7e-S6CpTShm",
  "CardId": "card_m_01HQ0J6H02QXH3HATEYW0FMJKP",
  "CardType": "CB_VISA_MASTERCARD",
  "CardRegistrationURL": "https://pci.sandbox.mangopay.com/api/mangopay/vault/tokenize/eyJjbGllbnQiOiJjbGllbnRJZCIsInRva2VuIjoidW5xaXVlVG9rZW4ifQ==",
  "ResultCode": "000000",
  "ResultMessage": "Success",
  "Currency": "EUR",
  "Status": "VALIDATED",
  "ProfilingAttemptReference": "25e5c450-7f00-4805-af04-4330e4dc0cee"
}

Managing cards

You can use the following endpoints to manage cards:

  • View a Card provides key information about the card, including its Fingerprint which can be used as an anti-fraud tool
  • Deactivate or edit a Card allows you to irreversibly set the card as inactive

Warning - End user’s approval needed to save card details

Under no circumstances should card information be kept without the end user’s approval.

If you don’t have the end user’s approval, you need to deactivate the card systematically after use in your implementation.

Requesting card pay-ins

You can use a registered card (CardId) for requests with the following API objects:

In your requests:

  • Ensure that the SecureModeReturnURL parameter is set to https://checkout.mangopay.com
  • Submit the PreferredCardNetwork value if it was received by onCreatePayment

Configuring Apple Pay

Note - Apple Pay integration required

Offering Apple Pay requires additional setup by the platform, including certification and integration. For more information, see the Apple Pay guide.

let applePayConfig = MGPApplePayConfig(
          amount: 1,
          delegate: self,
          merchantIdentifier: "<merchant_id>",
          merchantCapabilities: .capability3DS,
          currencyCode: "<currency_code",
          countryCode: "<country_code",
          supportedNetworks: [
              .masterCard,
              .visa
          ]
       )

let paymentConfig = PaymentMethodConfig(cardReg: cardRegObj, applePayConfig: applePayConfig)

checkout = MGPPaymentSheet.create(
       client: mgpClient,
       paymentMethodConfig: paymentConfig,
       branding: PaymentFormStyle(),
       callback: callback
   )

Apple Pay configuration parameters

PropertyTypeDescription
amountDouble REQUIREDThe amount being paid.
delegateMGPApplePayHandlerDelegate REQUIREDThe event handler.
merchantIdentifierStringThe merchant identifier. REQUIRED
merchantCapabilitiesPKMerchantCapability REQUIREDA bit field of the payment processing protocols and card types supported.
currencyCodeString REQUIREDThe three-letter ISO 4217 code (EUR, GBP, etc) of a supported currency (depends on feature, contract, and activation settings).
countryCodeString REQUIREDThe platform’s two-letter ISO 3166 country code.
supportedNetworksArray<PKPaymentNetwork> REQUIRED

The card networks supported by Mangopay.

Allowed values: VISA, MASTERCARD

requiredBillingContactFieldsSet<PKContactField>
billingContactPKContact
shippingContactPKContact
shippingTypePKShippingType
shippingMethodsArray<PKShippingMethod>
applicationDataData
requiredShippingContactFieldsSet<PKContactField>

Handling Apple Pay result

extension ViewController: MGPApplePayHandlerDelegate {

    func applePayContext(didSelect shippingMethod: PKShippingMethod, handler: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) {
    }

    func applePayContext(didCompleteWith status: MangoPayApplePay.PaymentStatus, error: Error?) {
    }
}

Configuring PayPal

let paypalOptions = MGPPaypalOptions()

PayPal configuration parameters

PropertyTypeDescription
colorPayPalButton.ColorColor of the paypal button. Default to gold if not provided.
edgesPaymentButtonEdgesEdges of the button. Default to softEdges if not provided.
labelPayPalButton.LabelLabel displayed next to the button’s logo. Default to no label.

Verifying the payment result

Once the onPaymentComplete event is triggered, verify the status of the relevant Mangopay API object:

Caution – Check payment result from backend

You should confirm the transaction result returned by the Checkout SDK by calling the Mangopay API from your backend.

Using Card Element

The Card Element offers a ready-made component that allows you to create your own card payment experience and tokenize card payment details. With our Card Element, you can easily incorporate a custom pay button and have control over the tokenization process.

When using Card Element, you still benefit from card data validation, and the ability to customize the payment form.

1. Create an instance of the MangopayCheckoutForm

lazy var elementForm: MGPPaymentForm = {
        let form = MGPPaymentForm(
            paymentFormStyle: PaymentFormStyle(),
            supportedCardBrands: [.visa, .mastercard, .maestro]
        )
        return form
    }()
MGPPaymentForm parameters
PropertyTypeDescription
paymentFormStylePaymentFormStyleProperty for styling the payment form.
supportedCardBrandsArray<CardType>The supported card brands listed above the payment form.

2. Add payment form to your parent view and add the appropriate layout constraints

self.view.addSubview(elementForm)

Using MangopayCheckoutForm with card tokenization

2.1 Create card registration object

2.2 Call tokenizeCard() when pay button is tapped

    MangopayCoreiOS.tokenizeCard(
        form: elementForm,
        with: cardRegistration,
        presentIn: <presenting_view_controller>
    ) { response, error in
            
      if let res = respoonse {
            //do something
      }
      
      if let err = error {
          //do something
      }
  }

MangopayCoreiOS.tokenizeCard()

PropertyTypeDescription
formMangopayCheckoutFormThe payment form instance.
withMGPCardRegistrationThe card registration object.
presentInUIViewController
callBacktypealias MangoPayTokenizedCallBack = ((TokenizedCardData?, MGPError?) -> ())A callback that handles events of the payment form tokenization process.

TokenizedCardData

PropertyTypeDescription
cardCardRegistrationTokenized Card object.
profilingAttemptReferenceStringThe unique reference for the profiling session.

Branding

You can customize the appearance of the payment sheet using the PaymentFormStyle object.

Example - Branding
let branding = PaymentFormStyle(
            font: .systemFont(ofSize: 12),
            borderType: .round,
            backgroundColor: .white,
            textColor: .gray,
            placeHolderColor: .darkGray,
            borderColor: .black,
            borderFocusedColor: .blue,
            errorColor: .red,
            checkoutButtonTextColor: .white,
            checkoutButtonBackgroundColor: .black,
            checkoutButtonDisabledBackgroundColor: .gray,
            checkoutButtonText: "Checkout",
            applePayButtonType: .plain,
            applePayButtonStyle: .black,
            applePayButtonCornerRadius: 8
         )

....

checkout = MGPPaymentSheet.create(
       client: mgpClient,
       paymentMethodConfig: paymentConfig,
       branding: branding,
       callback: callback
   )
PropertyTypeDescription
fontUIFontThe font of the text fields and labels.
borderTypeBorderTypeThe border type of the text fields.
Allowed values: square, round
textColorUIColorColor of the text in the text fields.
placeHolderColorUIColorThe color of the placeholder text in the text fields.
borderColorUIColorThe color of the text field borders.
borderFocusedColorUIColorThe color of the text field borders when highlighted.
errorColorUIColorThe color of the error labels.
checkoutButtonTextColorUIColorThe color of the text on the confirmation button.
checkoutButtonBackgroundColorUIColorThe color of the background of the confirmation button.
checkoutButtonDisabledBackgroundColorUIColorThe color of the background of the confirmation button when disabled.
checkoutButtonTextStringThe text of the confirmation button.
checkoutTitleTextStringThe text of the payment form title.
applePayButtonTypePKPaymentButtonTypeThe Apple Pay button type.
applePayButtonStylePKPaymentButtonStyleThe Apple Pay button style.
applePayButtonCornerRadiusCGFloatThe corner radius of the Apple Pay button.