# Android

> Learn how to integrate the pop-up payment experience SDK into an Android client.

In this topic, you'll learn how to integrate the pop-up payment experience SDK into an Android client. This will help you to render cashier pages in a mobile application.

---

## Prerequisites

Before the integration, ensure that you have completed the following tasks:

- Install the latest version of Android Studio.
- Use target API level 19 or later.
- Use Gradle 4.1 or later.
- Configure a physical machine or emulator to run your application.

---

## Key integration steps

Integrate the SDK by the following steps:

### Step 1: Integrate the SDK package

**Merchant client**

To integrate the SDK package, please refer to [Integrate the SDK Package for Android](https://docs.antom.com/ac/sdks/android.md).

### Step 2: Create an SDK instance by using `AMSCashierPayment`

**Merchant client**

The process of creating an SDK instance includes the following steps:

1. Create a *config* object: Required. The *object* must contain all of the following configuration parameters:
   - *setLocale*: Optional. String type. It is used to pass in language information. Valid values are listed as follows. If other values are passed, English is used by default:
     - `"en", "US"`: English
     - `"es", "ES"`: Spanish
     - `"fr", "FR"`: French
     - `"nl", "NL"`: Dutch
     - `"it", "IT"`: Italian
     - `"de", "DE"`: German
     - `"zh", "CN"`: Simplified Chinese
   - *setOption*: Optional, used to set whether to use a sandbox environment. Supported values include the following:
     - `"sandbox", "true"`: Sandbox environment.
     - `"sandbox", "false"`: Production Environment.
     - `"notRedirectAfterComplete", "true"`: Optional, Boolean type. The default value is `false`, which means it will jump back to your page after the payment is completed. The same applies when the value is empty. `true` value means there will be no jump after the payment is completed. You need to use the customer event code to control the card binding to complete the subsequent process. Please note that the payment result event code returned by the client is only used as a reference for the jump operation of the client page. For transaction status updates, please refer to the results returned by the server's [notifyPayment](https://docs.antom.com/ac/apo/notify_capture.md) or [inquiryPayment](https://docs.antom.com/ac/apo/paymentri_online.md) API.
     - *"merchantAppointmentParam"*: Optional object used for setting custom features. It contains a value below:
       - *storedCard*: Optional object used for setting custom features of stored cards. It contains a value below:
         - *needCVV*: Optional Boolean. The default value is `false`, which indicates that the user do not need to input CVV number during the payment process. The same applies when the value is empty. `true` value means the user need to input CVV number during the payment process.

2. Create an instance of the `onCheckoutListener` API for handling corresponding events in subsequent processes, including the following method:
   - `onEventCallback`: Required. A callback function that returns various types of data or values, including event codes, *cardPaymentResultInfo* parameter for card payment, and *popRiskDecisionResultInfo* parameter for risk control. See the [References](https://docs.antom.com/ac/sdks/overview.md) for further information.

3. Set the instance of the `onCheckoutListener` API to the *configuration* instance for executing event callbacks.

4. Instantiate the `AMSCashierPayment`.

**Example - Create an SDK instance:**

```java
AMSCashierPaymentConfiguration configuration = new AMSCashierPaymentConfiguration();
configuration.setLocale(new Locale("en", "US"));
// Set sandbox environment instead of online production environment.
configuration.setOption("sandbox", "true");
// Configure whether the payment button is rendered by the SDK component.
configuration.setOption("showSubmitButton", "true");
// After completing the payment, do not redirect and let the merchant control the subsequent process.
configuration.setOption("notRedirectAfterComplete", "true");
// The user need to input CVV number
configuration.setOption("merchantAppointParam", "{\n\t\"storedCard\": {\n\t\t\"needCVV\": true\n\t}\n}");
// Set up checkout callback monitoring.
configuration.setOnCheckoutListener(new OnCheckoutListener() {
    @Override
    public void onEventCallback(String eventCode, AMSEventResult eventResult) {
        Log.e(TAG, "onEventCallback eventCode=" + eventCode + " eventResult=" + eventResult.toString());
    }
});
// Create AMSCashierPayment instantiation.
AMSCashierPayment checkout = new AMSCashierPayment.Builder(activity, configuration).build();
```

### Step 3: Initiate a createPaymentSession request

**Merchant server**

The merchant client monitors the click events of the payment button itself. When the buyer selects the payment method and clicks the payment button, the merchant client initiates [createPaymentSession](https://docs.antom.com/ac/apo/payment_session.md) request to the APO server. Once the response to the [createPaymentSession](https://docs.antom.com/ac/apo/payment_session.md) request is received, the *paymentSessionData* value in the response is used in Step 4.

For card token payment mode with bound cards, you need to pass in the *paymentMethod.paymentMethodId* field to the card token returned to you by APO after the buyer binds the card. The way to obtain the card token is as follows:

- Independent card binding: Obtain the card token through the *card.cardToken* field in the asset binding result notification sent to you by APO.
- Non-independent card binding: Obtain the card token through the *paymentResultInfo.cardToken* field in the payment result notification sent to you by APO or the response to actively query the payment result.

> **Note**: When calling the [createPaymentSession](https://docs.antom.com/ac/apo/payment_session.md) API, the value of the request parameter *paymentRedirectUrl* needs to use the URL Scheme corresponding to the page you provide after the payment is completed.

**Example - createPaymentSession request (No card bound):**

```json
{
  "order": {
    "buyer": {
      "buyerName": {
        "firstName": "*****",
        "fullName": "D***u",
        "lastName": "Liu",
        "middleName": "Skr"
      },
      "buyerRegistrationTime": "2022-01-01T09:30:00+08:00",
      "referenceBuyerId": "tony.c"
    },
    "goods": [{
      "goodsBrand": "AMSDM",
      "goodsCategory": "card/ssr/adc",
      "goodsName": "Goods No.1",
      "goodsQuantity": "1",
      "goodsSkuName": "SKU1",
      "goodsUnitAmount": {
        "currency": "USD",
        "value": "10000"
      },
      "goodsUrl": "HangZhou LeiFenTa",
      "referenceGoodsId": "amsdm_good_tony_c_20230227_095825_922"
    }],
    "orderAmount": {
      "currency": "BRL",
      "value": "2129"
    },
    "orderDescription": "AMSDM_GIFT",
    "referenceOrderId": "amsdmorder_tony_c_20230227_095825_921"
  },
  "paymentAmount": {
    "currency": "BRL",
    "value": "2129"
  },
  "paymentFactor": {
    "isAuthorization": true
  },
  "paymentMethod": {
    "paymentMethodType": "CARD",
    "paymentMethodMetaData":{
        "paymentMethodRegion":"BR"
    }
  },
  "paymentNotifyUrl": "https://www.google.com.sg",
  "paymentRedirectUrl": "https://www.baidu.com",
  "paymentRequestId": "amsdmpayk_tony_c_20230227_095825_920_532",
  "productCode": "CASHIER_PAYMENT",
  "settlementStrategy": {
    "settlementCurrency": "USD"
  },
  "enableInstallmentCollection":"true"
}
```

**Example - createPaymentSession request (Token payment):**

```json
{
    "productCode": "CASHIER_PAYMENT",
    "paymentRequestId": "55bf93a6-71a1-4ca9-b014-53273bd674eb",
    "order": {
        "referenceOrderId": "926e1c32-4a6c-442e-b5ce-8ec5b902e18c",
        "orderDescription": "xxxxx",
        "orderAmount": {
            "currency": "EUR",
            "value": "100"
        },
        "buyer": {
            "referenceBuyerId": "yeiasdasda",
            "buyerPhoneNo": "134******71"
        }
    },
    "paymentAmount": {
        "currency": "EUR",
        "value": "100"
    },
    "paymentMethod": {
        "paymentMethodType": "CARD",
        "paymentMethodId": "alipayCardToken",
        "paymentMethodMetaData": {
          "isCardOnFile":true
        }
    },
    "paymentRedirectUrl": "https://www.yourMerchantWeb.com",
    "paymentNotifyUrl": "https://www.yourNotifyUrl",
    "paymentFactor": {
        "isAuthorization": true
    },
    "settlementStrategy": {
        "settlementCurrency": "EUR"
    }
}
```

**Example - Response for createPaymentSession request:**

```json
{
  "paymentSessionData": "UNvjVWnWPXJA4BgW+vfjsQj7PbOraafHY19X+6EqMz6Kvvmsdk+akdLvoShW5avHX8e8J15P8uNVEf/PcCMyXg==&&SG&&111",
  "paymentSessionExpiryTime": "2023-04-06T03:28:49Z",
  "paymentSessionId": "UNvjVWnWPXJA4BgW+vfjsQj7PbOraafHY19X+6EqMz6Ikyj9FPVUOpv+DjiIZqMe",
  "result": {
    "resultCode": "SUCCESS",
    "resultMessage": "success.",
    "resultStatus": "S"
  }
}
```

### Step 4: Create a payment element collection component using the `createComponent` method in the instance object

**Merchant client**

- Call the `createComponent()` method and pass in the following parameters:
  - *activity*: Required. Activity type object, used to contain contextual parameter information for the current page.
  - *sessionData*: Required. String type. Pass in the complete data of the *paymentSessionData* field obtained from the response of the [createPaymentSession](https://docs.antom.com/ac/apo/payment_session.md) request into the *sessionData* parameter.

- Free resources of the SDK component by calling the `onDestroy()` method in the instance object. You need to unmount a component in the following cases:
  - When the user exits the checkout page, free the component resources created in the [createPaymentSession](https://docs.antom.com/ac/apo/payment_session.md).
  - When the user initiates multiple payments, free the component resources created in the previous [createPaymentSession](https://docs.antom.com/ac/apo/payment_session.md).

**Example - Call the createComponent() method:**

```java
checkout.createComponent(activity,sessionData);
// Free SDK component resources
checkout.onDestroy();
```

---

## References

The References offers callback data and code samples for integration steps. For further details, refer to the [References](https://docs.antom.com/ac/sdks/ref.md).