# Flutter Android Integration
source: https://developer.mastercard.com/mastercard-gateway/documentation/integrations-types/mobile-integration/integrate-mobile-payments/mc-gw-andriod-sdk/flutter-android-integration/index.md

This SDK is packaged as a maven repository. Extract the SDK file into a directory within your project and include it as a repository in your project's `build.gradle` file.

Follow these steps to integrate Flutter Android SDK:

1. From your Merchant Admin portal, download the latest version of the SDK as a zip file.  

   For more information about downloading the SDK, see [Mobile SDK Integration](https://developer.mastercard.com/mastercard-gateway/documentation/integrations-types/mobile-integration/integrate-mobile-payments/mob-sdk-int/index.md).

2. Extract the SDK zip file in the root directory of your Android project. For example: \~/my-android- project/gateway- repo.

3. Add a reference to this local repository in your project's build.gradle file.

```groovy
// build.gradle
allprojects {
    repositories {
        mavenCentral()
        google()

        // Gateway Android SDK repo
        maven {
            url "$rootDir/gateway-repo"
        }
    }
}
```

4. In your app modules build.gradle file, include the Gateway SDK as a dependency. Warning: Replace 'X.X.X' with the current version number.

```groovy
// app/build.gradle
implementation 'com.mastercard.gateway:Mobile_SDK_Android:x.x.x'
```

The `Mobile_SDK_Android` folder contains a `maven-metadata.xml` file that has information to build the implementation reference for the library. The implementation gradle format is implementation `<groupId>:<artifactId>:<version>`.

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

To initialize the SDK in an Android application, implement the platform-specific code that handles method calls from Flutter.
Warning: Contact your payment service provider to know your gateway region.

Follow these steps to initialize the SDK:

1. Add the following code to handle SDK initialization.
2. Ensure that your `MethodChannel` is set up correctly to call the `initialiseGatewaySDK` method. This is typically done in the `MainActivity` or another appropriate place in your Android code.

```kotlin
fun initialiseGatewaySDK(arguments: Any?, result: MethodChannel.Result) {
    // Extract and cast arguments
    val args = arguments as? Map<*, *>
    val merchantId = args?.get("merchantId") as? String ?: ""
    val merchantName = args?.get("merchantName") as? String ?: ""
    val merchantUrl = args?.get("merchantUrl") as? String ?: ""
    val region = args?.get("region") as? String ?: ""

    // Convert region string to GatewayRegion enum
    val gatewayRegion = GatewayRegion.valueOf(region)

    // Initialize the GatewaySDK
    GatewaySDK.initialize(
        application,
        merchantId,
        merchantName,
        merchantUrl,
        gatewayRegion,
        UiCustomization(),
        success = { response ->
            // Handle the success response and invoke the callback function to update the Flutter code.
        },
        error = { throwable ->
            // Handle the error response and invoke the callback function to update the Flutter code.
        }
    )
}
```

3. Initialize the SDK from dart by referring to the following code:

```dart
// Define the MethodChannel
static const MethodChannel _channel = MethodChannel('com.yourcompany.gateway_sdk');

// Prepare arguments for the method call
final Map<String, dynamic> arguments = {
  'merchantId': merchantId,       // your merchant id
  'merchantName': merchantName,   // your merchant name
  'merchantUrl': merchantUrl,     // your merchant url
  'region': region,               // your region
};

// Invoke the method and handle the result
_channel.invokeMethod('initialiseGatewaySDK', arguments).then((result) {
  // Handle success result here
}).catchError((error) {
  // Handle error result here
});
```

### Session overview {#session-overview}

The Gateway SDK flow is based around the concept of a session. A session is a temporary container for any request fields and values of operations that reference a session. For more information, see the [Payment Session](https://developer.mastercard.com/mastercard-gateway/documentation/integrations-types/hosted-session/integrate-hosted-session/create-payment-session/index.md) documentation.

#### Key benefits {#key-benefits}

The key benefits are as follows:

* Reduces PCI compliance costs as you do not handle or store any payment details.
* Eases integration as you do not need to directly handle the values for the request fields stored in a session.
* Reduces internal fraud as your staff have limited access to payer's details.
* Allows you to update the request fields and values stored against a session. This is useful when a credit card expires or other details of a payer change.
* Allows you to retrieve the request fields and values contained in a session by specifying the session identifier.

### Create a session {#create-a-session}

Create a session with the gateway to initiate the payment flow on a mobile device.

To prepare the session for mobile transactions:

* Two API calls must be made.
* Ensure that these requests are made from your private server since they are protected by an API password.

|   Request Parameter   | Example |
|-----------------------|---------|
| `authenticationLimit` | 25      |

### Update the session {#update-the-session}

This table describes the request parameters to update the session.

|        Request Parameter        | Existence |       Example       |
|---------------------------------|-----------|---------------------|
| `order.id`                      | Required  | your-order-id       |
| `order.amount`                  | Required  | 1.23                |
| `order.currency`                | Required  | AUD                 |
| `authentication.acceptVersions` | Required  | 3DS2                |
| `authentication.channel`        | Required  | PAYER_APP           |
| `authentication.purpose`        | Required  | PAYMENT_TRANSACTION |

Warning: To authenticate the payer, load the specified API fields into the session before calling within the SDK. The API design determines how and when they are loaded into the session.

Once a session is created on your server, you should:

1. Return the session information back to the mobile application.
2. Pass this information to the SDK with the collected card information.

Warning: The apiVersion should remain the same for the whole transaction lifecycle, from session creation to final payment.

## Collecting card information {#collecting-card-information}

The SDK method to `updateSession` is optional to use but is recommended to help with the merchant server PCI scope. However, the card and token information can be loaded through a different API design and must be present in the session before the call is made in the SDK to authenticate the payer.

### Manual card entry {#manual-card-entry}

Follow these steps to make a manual card entry.

1. Pass the information directly to the gateway using an existing session ID.
2. To update card information, implement the platform-specific code to handle method call from Flutter.

```kotlin
fun updateSession(arguments: Any?, result: MethodChannel.Result) {
    // Extract and cast arguments from MethodChannel
    val args = arguments as? Map<*, *>
    val name = args?.get("nameOnCard") as? String ?: ""
    val number = args?.get("number") as? String ?: ""
    val expiryMonth = args?.get("month") as? String ?: ""
    val expiryYear = args?.get("year") as? String ?: ""
    val cvv = args?.get("securityCode") as? String ?: ""
    val sessionId = args?.get("sessionId") as? String ?: ""
    val currency = args?.get("currency") as? String ?: ""
    val amount = args?.get("amount") as? String ?: ""
    val orderId = args?.get("orderId") as? String ?: ""
    val apiVersion = args?.get("apiVersion") as? String ?: ""

    // The GatewayMap object provides support for building a nested map structure using key-based dot(.) notation.
    // Each parameter is similarly defined in your online integration guide.
    val request = GatewayMap().apply {
        set("sourceOfFunds.provided.card.nameOnCard", name)
        set("sourceOfFunds.provided.card.number", number)
        set("sourceOfFunds.provided.card.securityCode", cvv)
        set("sourceOfFunds.provided.card.expiry.month", expiryMonth)
        set("sourceOfFunds.provided.card.expiry.year", expiryYear)
    }

    // Prepare session object
    val session = Session(sessionId, amount, currency, apiVersion, orderId)

    // Call the API
    GatewayAPI.updateSession(session, request, callback)
}
```

3. You can invoke the update session method from Dart as follows:

```dart
// Assuming `gatewayChannel` is an object that has `invokeMethod` function
// and `updateSessionMethod` is a string representing the method name

gatewayChannel.invokeMethod(updateSessionMethod, {
  'nameOnCard': cardHolderName,     // Cardholder's name
  'number': cardNumber,             // Card number
  'securityCode': cvvCode,          // CVV code
  'month': expiryMonth,             // Expiry month
  'year': expiryYear,               // Expiry year
  'sessionId': sessionId,           // Session ID
  'amount': '1.97',                 // Amount to be processed
  'currency': 'USD',                // Currency code
  'orderId': 'your-order-id',       // Order ID
  'apiVersion': 61,                 // API version
});
```

### Tokenization {#tokenization}

The SDK provides support to update a session with card information. You can use that session to perform several operations with the gateway. Tokenization provides a way to retain a card on file and can be performed on your server with a valid session.

#### Create a card token {#create-a-card-token}

Follow these steps to use the mobile SDK to help creating a card token.

1. Create and Update a session using the SDK.
2. Update the session with the customer's card details through the Gateway SDK.GatewayAPIupdateSession method.
3. Return the Session ID to your server and call the Create or Update Token method on the Gateway with your private API credentials.
4. A token ID is returned and can be retained on your servers as a card-on-file.

For more information about Tokenization, see the [Create or Update Token](https://developer.mastercard.com/mastercard-gateway/documentation/api-reference/v100/rest/api-ops/index.md#tokenization) documentation.

### Google Pay {#google-pay}

The Gateway SDK includes a helper utility, called `GooglePayHandler`, for collecting card information from a Google Pay wallet.

Warning: You can integrate Google Pay using the native Android SDK. For more information, refer to [Google Pay](https://developer.mastercard.com/mastercard-gateway/documentation/integrations-types/mobile-integration/integrate-mobile-payments/mc-gw-andriod-sdk/index.md#google-pay).

<br />

### Payer authentication {#payer-authentication}

#### EMV 3-D Secure {#emv-3-d-secure}

EMV 3-D Secure or EMV 3-D Secure authentication is designed to protect online purchases against credit card fraud by allowing you to authenticate the payer before submitting an Authorization or Pay transaction.

The EMV 3-D Secure, also known as 3DS2 in the gateway, is the new version designed to enhance security in online purchases while providing frictionless checkouts to payers who are considered low risk by the Access Control Server (ACS).

The ACS may determine the risk using merchant information, device fingerprinting, previous interactions with the payer, or both. The ACS subjects the payer to a challenge, for example, entering a PIN, only where additional verification is required to authenticate the payer, thereby providing increased conversion rates.

Supported authentication schemes include Mastercard Identity Check, Visa Secure, and American Express SafeKey.

Authentication within the mobile SDKs is limited to 3DS2 only. If 3DS2 is not available, the authentication does not proceed. However, you can still proceed with the payment if the gateway recommends you do so.

For more information about EMV 3-D Secure Authentication, see the [EMV 3-D Secure Authentication](https://developer.mastercard.com/mastercard-gateway/documentation/security-and-fraud/authentication/3d-secure-auth/index.md) documentation.

### Authentication details {#authentication-details}

The embedded mobile SDK collects device metrics to send to the gateway along with your transaction information when you perform mobile SDK authentication, that is, verify the identity of a cardholder in a mobile app.

Provide as much information as possible about the payer and the transaction to increase the likelihood of the authentication being successful.

This additional information can be added to your session with an Update session request.

|             Parameter              | Existence |                              Description                              |
|------------------------------------|-----------|-----------------------------------------------------------------------|
| `order.merchantCategoryCode`       | Optional  | Same as the code in your merchant profile.                            |
| `billing.address parameter group`  | Optional  | It is recommended you include this in your request whenever possible. |
| `shipping.address parameter group` | Optional  | It is recommended you include this in your request whenever possible. |
| `customer parameter group`         | Optional  | It is recommended you include this in your request whenever possible. |

The device parameter group as seen in the documentation is only relevant for browser-based payments. It should not be used for mobile based payer authentications. These metrics help the system to determine how or if to authenticate the cardholder. During authentication, the user can expect to experience one of two authentication flows:

1. Frictionless: The Access Control Server (ACS) has collected enough information about the cardholder to authenticate them. No other action is needed by the user.
2. Challenge: The ACS requires the cardholder to complete an additional authentication step, which is to enter a onetime-password, login to their issuing bank, and so on. The embedded mobile SDK handles displaying a native device interface for this challenge. The UI for these screens can be customized by passing `UICustomization` params into the Gateway SDK during initialization.

For more information, see [Authenticate Payer](https://developer.mastercard.com/mastercard-gateway/documentation/api-reference/v100/rest/api-ops/index.md#authentication) documentation.

Warning: The parameter group for authentication.PSD2.exemption is currently not supported in the SDK.

<br />

### Perform authentication {#perform-authentication}

Payer authentication is considered a transaction on its own in the gateway, and therefore needs a unique transaction ID.

If you are collecting payment for an order, you can:

* Correlate a payment and an authentication transaction by using the same order ID for each transaction.
* Each transaction is displayed as a separate transaction in the gateway's web portal, such as UUID.

```kotlin
AuthenticationHandler.authenticate(
    activityContext,
    session,
    "your-auth-transaction-id",
    callback
)
```

Warning: The `your-auth-transaction-id` is a unique identifier for this transaction which distinguishes it from any other transaction on the order. This is needed as the gateway uses the `your-auth-transaction-id` to look up the authentication results that it stored when you asked the SDK to authenticate the payer. The gateway then passes the required information to the acquirer for the pay request.

### Interpret the response {#interpret-the-response}

The authenticate method returns an `AuthenticationResponse` object that contains:

* Important information about the outcome.
* Actions performed during the operation.

The most important field to consume is response.recommendation. It may contain the value PROCEED or DO_NOT_PROCEED.

* PROCEED: Indicates "OK to continue with a payment or authorization".
* DO_NOT_PROCEED: Indicates something failed during the authentication operation. The `AuthenticationError` object can be used to determine more.

From Mastercard Gateway API version 70 and later, you can get the following errors:

* `AuthenticationError.recommendation_ResubmitWithAlternativePaymentDetails`: Indicates that you should ask the payer for alternative payment details. For example, a new card or another payment method, and resubmit the request with the new details.
* `AuthenticationError.recommendation_AbandonOrder`: Indicates the payment service provider, scheme, or issuer require you to abandon the order.
* `AuthenticationError.recommendation_DoNotProceed`: Indicates that the gateway fails the request, but there is no way for this transaction to succeed.

For more information, see the Integration guides.

Follow these steps to perform authentication:

1. Implement the platform-specific code to handle method calls from Flutter.

```kotlin
fun authenticate(arguments: Any?, result: MethodChannel.Result) {

    // Retrieve sessionId, orderId, apiVersion and transactionID from call.arguments passed from dart code. Refer updateSession function
    val session = "your-session-object" // retrieve session object

    AuthenticationHandler.authenticate(this, session, authenticationId) { response ->

        val resultMap = hashMapOf<String, Any?>(
            "recommendation" to response.recommendation?.name,
            "authenticationPerformed" to response.authenticationPerformed,
            "challengePerformed" to response.challengePerformed,
            "error" to response.error?.message
        )

        when (response.recommendation) {
            AuthenticationRecommendation.PROCEED,
            AuthenticationRecommendation.DO_NOT_PROCEED -> result.success(resultMap)
            else -> result.error("UNKNOWN_ERROR", "Unknown error occurred during authentication", resultMap)
        }
    }
}
```

2. If the authentication fails, you can examine the response.error for more information about the cause.

```dart
// Assuming `gatewayChannel` is an object that has `invokeMethod` function
// and `authenticateMethod` is a string representing the method name
gatewayChannel.invokeMethod(authenticateMethod, {
  "session": 'session-object',
  "authenticationId": authenticationId,
}).then(result => {
  // Extract the recommendation from the result
  const recommendation = result['recommendation'];

  // Check the recommendation and handle accordingly
  if (recommendation === 'PROCEED') {
    // Continue to payment/authorization
    handlePaymentAuthorization();
  } else if (recommendation === 'DO_NOT_PROCEED') {
    // Handle Authentication not successful, re-enter card details
  }
});
```

