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

Prerequisites

For Android: 

  • Android minSdk = 21

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

The Mangopay Checkout SDK is published as a Maven artifact on Maven Central Repository.

Add the following code to your app/build.gradle file:

repositories {
  mavenCentral()
}

dependencies {
   implementation("com.mangopay.android:checkout-sdk:<latest-version>")
}

Optionally, to enable the fraud prevention Profiler SDK, add the following to settings.gradle.kts:

maven {
    url = uri("https://nethone.jfrog.io/artifactory/nethonesdk-android-mangopay/")
}

Initializing the SDK

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 Application() class.

MangopaySdk.initialize(
    context = this,
    clientId = “clientId”,
    profilingMerchantId = “profilingMerchantId”,
    tenantId = TenantId.EU,
    environment = Environment.SANDBOX,
    logLevel = LogLevel.Basic
)

Initialization parameters

PropertyTypeDescription
context Application The application context.
clientId String The unique identifier associated with the Mangopay API key, giving access to the Mangopay API.
profilingMerchantId Int The unique identifier associated with your fraud protection package. Contact Mangopay to obtain this value.
environment Environment The Mangopay environment. Allowed values: Environment.SANDBOX, Environment.PRODUCTION Default values: Environment.SANDBOX
logLevel LogLevel The specification of the HTTP request and response log. We recommend None for Production build.
Allowed values: LogLevel.None , LogLevel.Basic Default values: LogLevel.None
tenantId TenantId The identifier of the Mangopay tenant. Allowed values: TenantId.EU, TenantId.UK

Configuration

To configure the Checkout SDK’s payment sheet:

1

Configure the PaymentMethodOptions

Configure the options for each payment method as described below.

2

Present the payment sheet

Add PaymentMethodOptions and callbacks and display the payment sheet.

val paymentMethodOptions = PaymentMethodOptions.Builder()
        .cardOptions(cardOptions)
        .googlePayOptions(googlePayOptions) // OPTIONAL
        .paypalOptions(paypalOptions) // OPTIONAL
        .amount(amount)
        .build()

MangopayCheckoutSdk.create(
    mContext = this,
    paymentMethodOptions = paymentMethodOptions, 
    listener = paymentSheetCallbacks()
) 
PropertyTypeDescription
mContextActivity / FragmentActivity or Fragment context
paymentMethodOptionsPaymentMethodOptionsConfiguration parameters
listenerMangopay.PaymentSheetResultListenerCallback listeners

The payment sheet closes automatically when events are emitted to prevent users from clicking again.

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 onPaymentCompleted 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.

Creating payment handler callbacks

private fun paymentSheetCallbacks() = object : Mangopay.PaymentSheetResultListener {
    override fun onTokenizationCompleted(paymentMethod: PaymentMethod?, profilerAttemptReference: String?) {

        when (paymentMethod) {
            is PaymentMethod.CARD -> TODO()
            is PaymentMethod.GOOGLE_PAY -> TODO()
            else -> TODO()
        }
    }

    override fun onPaymentCompleted(id: String?, resultCode: ResultCode) {

    }

    override fun onPaymentMethodSelected(paymentMethod: PaymentMethod) {

    }

    override suspend fun onCreatePayment(paymentMethod: PaymentMethod, profilerAttemptReference: String?): Payment? {
        return when(paymentMethod){
            is PaymentMethod.PAYPAL -> TODO()
            is PaymentMethod.CARD -> TODO()
            is PaymentMethod.GOOGLE_PAY -> TODO()
            is GooglepayObject -> TODO()
        }
    }

    override suspend fun onCreateCardRegistration(card: Card): CardRegistration {

    }

    override fun onError(exception: MangopayException?) {

    }

    override fun onCancel() {

    }
}

PaymentSheet callbacks

CallbackDescriptionArgumentReturn type
onTokenizationCompleted(paymentMethod: PaymentMethod?, profilerAttemptReference: String?)Triggered when a card tokenization is completed and a CardId is returned.
onPaymentCompleted(id: String?, resultCode: ResultCode)Triggered when the transaction is completed, whatever the outcome (whether successful or failed).
onPaymentMethodSelected(paymentMethod: PaymentMethod)Triggered when a payment method has been selected.
onCreatePayment(paymentMethod: PaymentMethod, profilerAttemptReference: String?): Payment?Payment?
onCreateCardRegistration(card: Card): CardRegistration?Triggered only when the user selects card payment. This callback gives you control over making the card registration optional during the session.CardRegistration?
onError(exception: MangopayException?)Triggered when an internal Checkout SDK error has occurred, which propagates the exception.
onCancel()Called when the payment sheet is closed.

The payment sheet automatically closes when events are emitted to prevent users from clicking again.

Configuring the amount

val amount = Amount.Builder()
        .value(200.00)
        .currency(Currency.EUR)
        .build()

Amount configuration parameters

PropertyTypeDescription
valueDouble
currencyCurrency

Configuring card payments

val cardOptions = CardOptions.Builder()
                    .supportedCardSchemes(
                        listOf(CardScheme.Maestro,CardScheme.MasterCard,CardScheme.Visa,)
                    )
                    .build()

Card configuration parameters

PropertyTypeDescription
supportedCardSchemes List<Card> The card networks displayed to the user.
cardRegistration CardRegistration? You can provide CardRegistration optionally from configuration or provide it from callbacks.

Handling 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.

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 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

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.

Configuring Google Pay

Note – Google Pay setup required

Offering Google Pay requires additional setup by the platform. For more information, see the How to process a Google Pay payment tutorial. 

To offer the Google Pay payment method, include the GooglePayOptions in the payment sheet:

  1. Configure TransactionInfo object
  2. Create GooglePay object
  3. Configure GooglePayObject

val transactionInfo = TransactionInfo.Builder()
        .currencyCode("EUR")
        .countryCode("FI")
        .totalPriceStatus(TotalPriceStatus.FINAL)
        .totalPrice(5000.0)
        .transactionId(UUID.randomUUID().toString())
        .build()

val cardParameters = CardParameters.Builder()
       .allowedAuthMethods(listOf("PAN_ONLY", "CRYPTOGRAM_3DS"))
       .allowedCardNetworks(listOf( "MASTERCARD", "VISA"))
       .build()

val googlePayObject = GooglePayObject.Builder()
        .merchantName("Example Test")
        .gatewayMerchantId("your-mangopay-client-id")  
        .transactionInfo(transactionInfo)
        .cardParameters(cardParameters)
        .build()

val googlePayOptions = GooglePayOptions.Builder()
        .googlePayObject(googlePayObject)
        .build()

Google Pay Parameters

PropertyTypeDescription
gatewayMerchantIdStringYour Mangopay ClientId.
transactionInfoTransactionInfoInformation about the transaction. For more information on this object parameter, see the Google Pay documentation.
cardParametersCardParametersInformation about the card used for the payment.

CardParameters required parameters

PropertyTypeDescription
allowedAuthMethodsList<String>

The supported authentication methods:

  • PAN_ONLY, meaning the card is registered in the user’s Google account and requires additional authentication;
  • CRYPTOGRAM_3DS, meaning the card is enrolled in the customer’s Google Wallet and authentication is handled by Google, with no 3DS redirection and no liability for the platform.

Allowed values: PAN_ONLY, CRYPTOGRAM_3DS

allowedCardNetworksList

The card networks supported by Mangopay: VISA and MASTERCARD.

Allowed values: VISA, MASTERCARD

TransactionInfo required parameters

PropertyTypeDescription
countryCodeString
currencyCodeString
totalPriceStatusTotalPriceStatus
totalPriceDouble

Requesting Google Pay pay-in

To request the payment, use the Create a Google Pay PayIn endpoint and include the Google Pay PaymentData provided by the Checkout SDK.

Configuring PayPal

val paypalOptions = PaypalOptions.Builder()
          .buttonOptions(buttonOptions)
          .build()

PayPal configuration parameters

PropertyTypeDescription
buttonOptionsPaymentButtonOptions

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. Add the payment form to the intended layout

<com.mangopay.android.checkout.view.PaymentFormView
            android:id="@+id/payment_form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:mangopay_elementBorderLineType="rectangle" />


<!-- Add custom pay button -->
<Button
            android:id="@+id/btn_pay"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible"
            android:layout_below="@+id/payment_form"
            android:layout_marginTop="50dp"
            android:text="Pay" />

2. Create the Card Registration as described above

val cardRegistration = CardRegistration.Builder()
        .id("Id")
        .userId("UserId")
        .accessKey("AccessKey")
        .preRegistrationData("PreRegistration")
        .cardRegistrationURL("CardRegistrationURL")
        .build()

3. Tokenize the card with the paymentForm object


//Find and connect PaymentFormView from Java/Kotlin code
val paymentForm = findViewById<PaymentFormView>(R.id.payment_form)
val payButton = findViewById<PaymentFormView>(R.id.btn_pay)
// tokenize card with the paymentForm object.
 payButton.setOnClickListener {

    //check if the paymentForm passed validation
    if(paymentForm.isComplete()){

            MangopayCheckoutSdk.tokenizeCard(
     paymentForm.toCardRequest(), cardRegistration,
       this@PaymentFormActivity, object: Mangopay.CheckoutTokenizeCardResultCallback {

             override fun success(result: CardResult?, attemptReference: String?) {
                 //process payment in your backend
             }
             override fun error(exception: MangopayException) {
                 //show error to shopper 
             }
           }
        )
    }
 }

Branding

You can customize the appearance of the payment sheet by adding a theme.xml file to the PaymentFormView object.

PropertyType
mangopay_elementTopLabelColorColor
mangopay_elementInputColorColor
mangopay_elementInputHintColorColor
mangopay_elementTopLabelSizeDimension
mangopay_elementTopLabelString
mangopay_buttonBackgroundColorColor
mangopay_buttonTextColorColor
mangopay_progressBarColorColor
mangopay_elementBorderLineTypeEnum
Example – Theme
<style name="Theme.ShuFitness" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/shopping_primary</item>
        <item name="colorPrimaryVariant">@color/shopping_primary</item>
        <item name="colorOnPrimary">@color/white</item>

        <item name="mangopay_elementTopLabelColor">@color/black</item>
        <item name="mangopay_elementInputColor">@color/black</item>
        <item name="mangopay_elementTopLabelSize">@dimen/top_label_size</item>
        <item name="mangopay_elementInputHintColor">@color/black</item>
        <item name="mangopay_progressBarColor">@color/shopping_secondary</item>
    </style>

You can add your theme to the application in AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.ShuFitness">

Configuring the Google Pay button

Configure the Google Pay button for your app in line with Google Pay’s brand guidelines.

Example – Google Pay configuration
val paymentMethods = JSONArray().put(PaymentsUtil.baseCardPaymentMethod())
val gpayButtonOption = ButtonOptions.newBuilder()
       .setButtonTheme(ButtonConstants.ButtonTheme.LIGHT)
       .setButtonType(ButtonConstants.ButtonType.BUY)
       .setAllowedPaymentMethods(paymentMethods.toString())
       .setCornerRadius(10)
       .build()

Localization

The Mangopay Checkout SDK allows you to localize language strings.

PropertyType
mangopay_elementTopLabelString
mangopay_buttonCheckoutTextString
mangopay_cardNumberHintString
mangopay_cardNumberErrorString
mangopay_cardNameHintString
mangopay_cardNameErrorString
mangopay_cardMMYYHintString
mangopay_cardMMYYErrorString
mangopay_cardCVVHintString
mangopay_cardCVVErrorString
mangopay_orPayWithTextString
mangopay_sheetAppBarTextString