Checkout - iOS
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 Hub - 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+
Installation
Mangopay Checkout
Swift Package Manager (recommended)
- 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
Creating a Card Registration
In your backend, create the Card Registration via the Mangopay API, using the Id
of the user as the UserId
.
You must also define the currency and type of the card at this stage.
{
"Tag": "Created with the Mangopay Checkout SDK",
"UserId": "142036728",
"CardType": "CB_VISA_MASTERCARD",
"Currency": "EUR"
}
{
"Id": "193020188",
"Tag": ,
"CreationDate": 1686147148,
"UserId": "193020185",
"AccessKey": "1X0m87dmM2LiwFgxPLBJ",
"PreregistrationData": "XBDYiG8w9PrylPS01KmupZunmK2QRHKIC-yUF6il3aIpAnKba1TGkR9VJe5lHjHt2ddFLVXdicolcUIkv_kKEA",
"RegistrationData": ,
"CardId": ,
"CardType": "CB_VISA_MASTERCARD",
"CardRegistrationURL": "https://pci.sandbox.mangopay.com/api/mangopay/vault/tokenize/eyJjbGllbnQiOiJjbGllbnRJZCIsInRva2VuIjoidW5xaXVlVG9rZW4ifQ==",
"ResultCode": ,
"ResultMessage": ,
"Currency": "EUR",
"Status": "CREATED"
}
The data obtained in the response will be used in the options
of the card payment method configured below.
Initializing the SDK
Initialize the SDK with your ClientId
and select your environment (Sandbox or Production).
MangopayCheckoutSDK.initialize(clientId: "<client_id>", environment: .sandbox)
Initialization parameters
Property | Type | Description |
---|---|---|
clientId | String | The unique identifier associated with the Mangopay API key, giving access to the Mangopay API. |
environment | Environment | The Mangopay environment. |
Configuring the payment sheet
To configure the Checkout SDK’s payment sheet:
1. Create a payment sheet instance in your view controller
var checkout: MGPPaymentSheet!
2. Create callbacks to handle the payment
let callback = CallBack(
onPaymentMethodSelected: { paymentMethod in
},
onTokenizationCompleted: { cardRegistration in
}, onPaymentCompleted: {
}, onCancelled: {
},
onError: { error in
},
onSheetDismissed: {
}
)
3. Create the paymentMethodConfig object
let paymentConfig = PaymentMethodConfig(cardReg: cardRegObj)
4. Initialize the payment sheet
checkout = MGPPaymentSheet.create(
client: mgpClient,
paymentMethodConfig: paymentConfig,
handlePaymentFlow: false,
branding: PaymentFormStyle(),
callback: callback
)
5. Present the payment sheet
checkout.present(in: self)
paymentMethodConfig parameters
Property | Type | Description |
---|---|---|
card | MGPCardInfo | Information about the card used for the payment. |
cardReg | MGPCardRegistration | Information obtained from the Mangopay Card Registration object. |
applePayConfig | MangopayApplePayConfig | The configuration options for Apple Pay. |
Using Card Element
Card Element is a ready-made component that allows you to create your own card payment experience and tokenize card payment details. With Card Element, you can 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.
To use Card Element, proceed as follows:
1. Create an instance of the payment form
lazy var elementForm: MGPPaymentForm = {
let form = MGPPaymentForm(
paymentFormStyle: PaymentFormStyle(),
supportedCardBrands: [.visa, .mastercard, .maestro]
)
return form
}()
MGPPaymentForm
Property | Type | Description |
---|---|---|
paymentFormStyle | PaymentFormStyle | Property for styling the payment form. |
supportedCardBrands | Array | The card networks displayed to the user. Allowed values: visa, mastercard, maestro |
2. Add payment form to your parent view and add the appropriate layout constraints
self.view.addSubview(elementForm)
3. Create Card Registration object as described above
4. Call tokenizeCard() on user action
The example below is for the user clicking on the pay button.
MangopayCoreiOS.tokenizeCard(
form: elementForm,
with: cardRegistration,
presentIn: <presenting_view_controller>
) { respoonse, error in
if let res = respoonse {
//do something
}
if let err = error {
//do something
}
}
MangopayCoreiOS.tokenizeCard()
Property | Type | Description |
---|---|---|
form | MangopayCheckoutForm | The Mangopay payment form. |
with | MGPCardRegistration | The Mangopay API Card Registration object. |
presentIn | UIViewController | |
callBack | typealias MangoPayTokenizedCallBack = ((TokenizedCardData?, MGPError?) -> ()) | A callback that handles events of the payment form tokenization process. |
TokenizedCardData
Property | Type | Description |
---|---|---|
card | CardRegistration | The tokenized Card Registration object with CardId . |
fraud | FraudData | Data regarding fraud risk management. |
FraudData
Property | Type | Description |
---|---|---|
provider | String | Fraud risk management data provider: Nethone. |
profilingAttemptReference | String | Profiling attempt reference provided by Nethone. |
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 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 pay-ins with the following objects:
- The Direct Card PayIn object, for one-shot card payments
- The Recurring PayIn Registration object, for recurring card payments
- The Preauthorization object, for 7-day preauthorized card payments
- The Deposit Preauthorization object, for 30-day preauthorized card payments
Note - 3DS redirection required when requesting card payments
When you make a card payment request, you need to be ready to handle 3DS redirection.
Handling 3DS redirection
When requesting a payment or other card authorization, you need to be able to handle 3DS redirection if it is required by the issuer. This is indicated by the SecureModeNeeded
in the API response, and the SecureModeRedirectURL
provides the redirection URL.
The Checkout SDK’s 3DS helper allows you to redirect users to authenticate securely and seamlessly.
Note - Example project for 3DS handling
You can find an example of handling 3DS redirect flow using our SDK in the HandleThreedsActivity.tk file from the Mangopay iOS SDK examples.
let _3dsVC = ThreeDSController(
secureModeReturnURL: <"secure_mode_url">,
secureModeRedirectURL: "secure_mode_redirect_url",
transactionType: .cardDirect,
onComplete: { result in
switch result.status {
case .SUCCEEDED:
//do something
case .FAILED:
//do something
}
}) { error in
}
viewController.present(_3dsVC)
3DS helper parameters
Property | Type | Description |
---|---|---|
secureModeRedirectURL | String | The URL to which users are redirected to authenticate with 3DS (if required). |
secureModeReturnURL | String | The URL to which users are returned after the payment, whether a 3DS challenge was triggered or not and whatever the transaction outcome. |
transactionType | _3DSTransactionType | The type of the authorization request. |
onComplete | (_3DSResult) -> () | Callback to handle successful or failed authentication requests. |
onError | (Error?) -> () | Callback to handle 3DS redirection errors. |
_3DSTransactionType
Property | Description |
---|---|
cardDirect | A Direct Card PayIn. |
preauthorized | A card Preauthorization. |
cardValidated | A Card Validation. |
_3DSResult
Property | Type | Description |
---|---|---|
secureModeRedirectURL | String | The URL to which users are redirected to authenticate with 3DS (if required). |
secureModeReturnURL | String | The URL to which users are returned after the payment, whether a 3DS challenge was triggered or not and whatever the transaction outcome. |
transactionType | _3DSTransactionType | The type of the authorization request. |
onComplete | (_3DSResult) -> () | Callback to handle successful or failed authentication requests. |
onError | (Error?) -> () | Callback to handle 3DS redirection errors. |
Verifying the payment result
Best practice - Check payment result from backend
It is highly recommended that you confirm the transaction result from your backend using the API endpoint.
Presenting the payment result
Checkout Screen -> Payment sheet -> Confirmation screen
checkout = MGPPaymentSheet.create(
paymentMethodConfig: 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)
Offering 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 How to process an Apple Pay payment tutorial.
To offer the Apple Pay payment method, include the MangopayApplePayConfig
object during initialization. This displays the Apple Pay button and handle Apple Pay payment events.
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
)
Configuration parameters
Property | Type | Description |
---|---|---|
amount | Double | The amount being paid. |
delegate | MGPApplePayHandlerDelegate | The event handler. |
merchantIdentifier | String | Your platform’s Apple Pay Merchant ID. |
merchantCapabilities | PKMerchantCapability | Information about the card types and authentication protocols you support (see Apple Pay documentation). |
currencyCode | String | The three-letter ISO 4217 code (EUR, GBP, etc) of a supported currency (depends on feature, contract, and activation settings). |
countryCode | String | The platform’s two-letter ISO 3166 country code. |
supportedNetworks | Array | The card networks supported by Mangopay: VISA and MASTERCARD. Allowed values: VISA, MASTERCARD |
Optional parameters
Property | Type | Description |
---|---|---|
requiredBillingContactFields | Array | The billing information to fulfill the order. |
requiredShippingContactFields | Set | The shipping information to fulfill the order. |
billingContact | PKContact | The billing contact information for the user. |
shippingContact | PKContact | The shipping contact information for the user. |
shippingType | PKShippingType | |
shippingMethods | Array | |
applicationData | Data |
Handling the Apple Pay result
extension ViewController: MGPApplePayHandlerDelegate {
func applePayContext(didSelect shippingMethod: PKShippingMethod, handler: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) {
}
func applePayContext(didCompleteWith status: MangoPayApplePay.PaymentStatus, error: Error?) {
}
}
Requesting Apple Pay pay-in
To request the payment, use the Create a Apple Pay PayIn endpoint and include the Apple Pay PaymentData
.
Branding
You can customize the appearance of the payment sheet using the PaymentFormStyle
object.
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
)
Property | Type | Description |
---|---|---|
font | UIFont | The font of the text fields and labels. |
borderType | BorderType | The border type of the text fields. Allowed values: square , round |
textColor | UIColor | Color of the text in the text fields. |
placeHolderColor | UIColor | The color of the placeholder text in the text fields. |
borderColor | UIColor | The color of the text field borders. |
borderFocusedColor | UIColor | The color of the text field borders when highlighted. |
errorColor | UIColor | The color of the error labels. |
checkoutButtonTextColor | UIColor | The color of the text on the confirmation button. |
checkoutButtonBackgroundColor | UIColor | The color of the background of the confirmation button. |
checkoutButtonDisabledBackgroundColor | UIColor | The color of the background of the confirmation button when disabled. |
checkoutButtonText | String | The text of the confirmation button. |
checkoutTitleText | String | The text of the payment form title. |
applePayButtonType | PKPaymentButtonType | The Apple Pay button type. |
applePayButtonStyle | PKPaymentButtonStyle | The Apple Pay button style. |
applePayButtonCornerRadius | CGFloat | The corner radius of the Apple Pay button. |