> ## Documentation Index
> Fetch the complete documentation index at: https://www.cashfree.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Android Integration

> Integrate the Cashfree Payment Gateway Android SDK to add UPI Intent, web checkout, and seamless payment flows to your native Android app with minimal code.

<div class="hidden mb-4" data-table-of-contents="top">
  <iframe height="150" width="100%" class="shadow-2xl rounded-md" src="https://www.youtube.com/embed/J1fIqjgiMeY?enablejsapi=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen />

  <a href="https://www.cashfree.com/devstudio/preview/pg/mobile/android" target="_blank" class="inline-flex items-center justify-center mt-4 p-4 w-full text-base font-medium text-gray-500 rounded-lg bg-gray-50 hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:bg-gray-800 dark:hover:bg-gray-700 dark:hover:text-white">
    <span class="flex items-center gap-2">
      Try it in DevStudio

      <svg width="20px" height="20px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M14 4H20M20 4V10M20 4L12 12" stroke="#33363F" stroke-width="2" />

        <path d="M11 5H7C5.89543 5 5 5.89543 5 7V17C5 18.1046 5.89543 19 7 19H17C18.1046 19 19 18.1046 19 17V13" stroke="#33363F" stroke-width="2" stroke-linecap="round" />
      </svg>
    </span>
  </a>
</div>

Cashfree's Android SDK provides a comprehensive payment solution that integrates the payment gateway into your Android applications, supporting Android SDK version 19 and above. The SDK offers multiple checkout flows including web checkout and UPI Intent checkout.

## Key benefits

The Android SDK offers the following advantages for your payment integration:

* **Multiple checkout flows**: Provides web checkout and UPI Intent checkout options to suit different integration needs.

* **Native Android support**: Optimised for Android SDK version 19 and above with native UI components for UPI payments.

* **Customisable UI**: Allows customisation of themes, colours, and fonts to match your app's design.

* **Secure and compliant**: Securely handles payment processing with built-in security measures managed by the SDK.

## Prerequisites

Ensure you complete the following tasks before starting the integration:

* Create a [Cashfree Merchant Account](https://merchant.cashfree.com/merchants/signup).
* Log in to the [Merchant Dashboard](https://merchant.cashfree.com/auth/login) and generate an **App ID** and **Secret Key**. Learn how to [generate API keys](/api-reference/authentication#generate-api-keys).
* Ensure your application complies with Cashfree's [Integrity standards](/payments/online/mobile/misc/cashfree_integrity). Applications that don't meet the required integrity standards may be restricted from using production services.

The Android integration consists of three essential steps:

<CardGroup cols={3}>
  <Card title="Step 1" icon="money-bill-wave" href="/payments/online/mobile/android#step-1-create-an-order-server-side">
    Create an order
  </Card>

  <Card title="Step 2" icon="desktop" href="/payments/online/mobile/android#step-2-open-the-checkout-page-client-side">
    Open the checkout page
  </Card>

  <Card title="Step 3" icon="circle-check" href="/payments/online/mobile/android#step-3-confirm-the-payment-server-side">
    Confirm the payment
  </Card>
</CardGroup>

The step-by-step guide for each step of the integration process is as follows:

## Step 1: Create an order <Badge color="green">Server-side</Badge>

To integrate the Cashfree Payment Gateway, you must first create an order. Complete this step before you process any payments. Configure an endpoint on your server to handle order creation. You can't call this API from the client-side.

<Note>Create orders through your server as this API requires your secret key. Don't call it directly from your mobile application.</Note>

##### API request for creating an order

Here's a sample request for creating an order using your desired backend language. Cashfree offers backend [SDKs](/api-reference/payments/sdk#payment-sdk) to simplify the integration process.

<CodeGroup>
  ```javascript javascript theme={"dark"}
  import { Cashfree, CFEnvironment } from "cashfree-pg";

  const cashfree = new Cashfree(
  	CFEnvironment.PRODUCTION,
  	"{Client ID}",
  	"{Client Secret Key}"
  );

  function createOrder() {
  	var request = {
  		order_amount: "1",
  		order_currency: "INR",
  		customer_details: {
  			customer_id: "node_sdk_test",
  			customer_name: "",
  			customer_email: "example@gmail.com",
  			customer_phone: "9999999999",
  		},
  		order_meta: {
  			return_url:
  				"https://test.cashfree.com/pgappsdemos/return.php?order_id=order_123",
  		},
  		order_note: "",
  	};

  	cashfree
  		.PGCreateOrder(request)
  		.then((response) => {
  			var a = response.data;
  			console.log(a);
  		})
  		.catch((error) => {
  			console.error("Error setting up order request:", error.response.data);
  		});
  }
  ```

  ```python python theme={"dark"}
  from cashfree_pg.models.create_order_request import CreateOrderRequest
  from cashfree_pg.api_client import Cashfree
  from cashfree_pg.models.customer_details import CustomerDetails


  Cashfree.XClientId = {Client ID}
  Cashfree.XClientSecret = {Client Secret Key}
  Cashfree.XEnvironment = Cashfree.XSandbox
  x_api_version = "2023-08-01"

  def create_order():
          customerDetails = CustomerDetails(customer_id="123", customer_phone="9999999999")
          createOrderRequest = CreateOrderRequest(order_amount=1, order_currency="INR", customer_details=customerDetails)
          try:
              api_response = Cashfree().PGCreateOrder(x_api_version, createOrderRequest, None, None)
              print(api_response.data)
          except Exception as e:
              print(e)
  ```

  ```java java theme={"dark"}
  import com.cashfree.*;

  Cashfree.XClientId = {Client Key};
  Cashfree.XClientSecret = {Client Secret Key};
  Cashfree.XEnvironment = Cashfree.SANDBOX;

  static void createOrder() {
    CustomerDetails customerDetails = new CustomerDetails();
    customerDetails.setCustomerId("123");
    customerDetails.setCustomerPhone("9999999999");

    CreateOrderRequest request = new CreateOrderRequest();
    request.setOrderAmount(1.0);
    request.setOrderCurrency("INR");
    request.setCustomerDetails(customerDetails);
    try {
      Cashfree cashfree = new Cashfree();
      ApiResponse<OrderEntity> response = cashfree.PGCreateOrder("2023-08-01", request, null, null, null);
      System.out.println(response.getData().getOrderId());

    } catch (ApiException e) {
      throw new RuntimeException(e);
    }
  }
  ```

  ```go go theme={"dark"}
  import (
    cashfree "github.com/cashfree/cashfree-pg/v3"
  )

  func createOrder() {

  clientId := {Client ID}
  clientSecret := {Client Secret Key}
  cashfree.XClientId = &clientId
  cashfree.XClientSecret = &clientSecret
  cashfree.XEnvironment = cashfree.SANDBOX

  request := cashfree.CreateOrderRequest{
  		OrderAmount: 1,
  		CustomerDetails: cashfree.CustomerDetails{
  			CustomerId:    "1",
  			CustomerPhone: "9999999999",
  		},
  		OrderCurrency: "INR",
  		OrderSplits:   []cashfree.VendorSplit{},
  	}
  	version := "2023-08-01"
  	response, httpResponse, err := cashfree.PGCreateOrder(&version, &request, nil, nil, nil)
  	if err != nil {
  		fmt.Println(err.Error())
  	} else {
  		fmt.Println(httpResponse.StatusCode)
  		fmt.Println(response)
      }
  }
  ```

  ```csharp csharp theme={"dark"}
  using cashfree_pg.Client;
  using cashfree_pg.Model;

  Cashfree.XClientId = {Client ID};
  Cashfree.XClientSecret = {Client Secret Key};
  Cashfree.XEnvironment = Cashfree.PRODUCTION;
  var cashfree = new Cashfree();
  var xApiVersion = "2023-08-01";

  void CreateOrder() {
      var customerDetails = new CustomerDetails("123", null, "9999999999");
      var createOrdersRequest = new CreateOrderRequest(null, 1.0, "INR", customerDetails);
      try {
          // Create Order
          var result = cashfree.PGCreateOrder(xApiVersion, createOrdersRequest, null, null, null);
          Console.WriteLine(result);
          Console.WriteLine(result.StatusCode);
          Console.WriteLine((result.Content as OrderEntity));
      } catch (ApiException e) {
          Console.WriteLine("Exception when calling PGCreateOrder: " + e.Message);
          Console.WriteLine("Status Code: " + e.ErrorCode);
          Console.WriteLine(e.StackTrace);
      }
  }
  ```

  ```php php theme={"dark"}
  \Cashfree\Cashfree::$XClientId = "<x-client-id>";
  \Cashfree\Cashfree::$XClientSecret = "<x-client-secret>";
  \Cashfree\Cashfree::$XEnvironment = Cashfree\Cashfree::$SANDBOX;

  $cashfree = new \Cashfree\Cashfree();

  $x_api_version = "2023-08-01";
  $create_orders_request = new \Cashfree\Model\CreateOrdersRequest();
  $create_orders_request->setOrderAmount(1.0);
  $create_orders_request->setOrderCurrency("INR");
  $customer_details = new \Cashfree\Model\CustomerDetails();
  $customer_details->setCustomerId("123");
  $customer_details->setCustomerPhone("9999999999");
  $create_orders_request->setCustomerDetails($customer_details);

  try {
      $result = $cashfree->PGCreateOrder($x_api_version, $create_orders_request);
      print_r($result);
  } catch (Exception $e) {
      echo 'Exception when calling PGCreateOrder: ', $e->getMessage(), PHP_EOL;
  }
  ```

  ```bash curl theme={"dark"}
  curl --location 'https://sandbox.cashfree.com/pg/orders' \
  --header 'X-Client-Secret: {{clientKey}}' \
  --header 'X-Client-Id: {{clientId}}' \
  --header 'x-api-version: 2025-01-01' \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  --data-raw '{
    "order_amount": 10.10,
    "order_currency": "INR",
    "customer_details": {
      "customer_id": "USER123",
      "customer_name": "joe",
      "customer_email": "joe.s@cashfree.com",
      "customer_phone": "+919876543210"
    },
    "order_meta": {
      "return_url": "https://b8af79f41056.eu.ngrok.io?order_id=order_123"
    }
  }'
    }

  }'
  ```
</CodeGroup>

After successfully creating an order, you will receive a unique `order_id` and `payment_session_id` that you need for subsequent steps.

You can view all the complete API request and response for `/orders` [here](/api-reference/payments/latest/orders/create).

## Step 2: Open the checkout page <Badge color="orange">Client-side</Badge>

Once the order is created, the next step is to open the payment page so the customer can make the payment.

### 1. Set up the SDK

The Cashfree Android SDK is hosted on Maven Central. You can download the latest version [2.4.0](https://github.com/cashfree/nextgen-android). The Android SDK supports Android SDK version 19 and above.

Add the following dependency to your app's `build.gradle` file:

```gradle theme={"dark"}
implementation 'com.cashfree.pg:api:2.4.0'
```

### 2. Select a payment flow

The Android SDK offers the following payment flows:

<AccordionGroup>
  <Accordion title="Web Checkout">
    In this flow, the SDK provides a webview-based checkout implementation to facilitate a quick integration with the payment gateway. Your customers can fill in the necessary details in the web page and complete the payment.
    This mode handles all the business logic and UI components to make the payment smooth and easy to use.
  </Accordion>

  <Accordion title="UPI Intent Checkout">
    This flow is for merchants who want to provide UPI Intent functionality using Cashfree's mobile SDK. In this flow, the SDK provides a pre-built native Android screen to facilitate integration with the payment gateway. Your customers see a list of UPI apps installed on their phone which they can select to initiate payment.
    This mode handles all the business logic and UI components to make the payment smooth and easy to use. The SDK allows you to customise the UI in terms of colour coding and fonts.
  </Accordion>
</AccordionGroup>

### 3. Complete the payment

To complete the payment, follow these steps:

1. Create a `CFSession` object.
2. Create a `CFTheme` object.
3. Create a `CFWebCheckoutPayment` or `CFUPIIntentCheckoutPayment` object.
4. Set up payment callback.
5. Initiate the payment using the payment object.

#### Create a session

This object contains essential information about the order, including the payment session ID (`payment_session_id`) and order ID (`order_id`) obtained from Step 1. It also specifies the environment (sandbox or production).

<CodeGroup>
  ```java java theme={"dark"}
  CFSession cfSession = new CFSession.CFSessionBuilder()
          .setEnvironment(CFSession.Environment.SANDBOX)
          .setPaymentSessionID("paymentSessionID")
          .setOrderId("orderID")
          .build();
  ```

  ```kotlin kotlin theme={"dark"}
  val cfSession = CFSessionBuilder()
      .setEnvironment(CFSession.Environment.SANDBOX)
      .setPaymentSessionID("paymentSessionID")
      .setOrderId("orderID")
      .build()
  ```
</CodeGroup>

#### Customise theme (optional)

You can customise the appearance of the checkout screen using CFTheme. This step is optional but can help maintain consistency with your app's design.

<AccordionGroup>
  <Accordion title="Web Checkout">
    <CodeGroup>
      ```java java theme={"dark"}
      CFWebCheckoutTheme cfTheme = new CFWebCheckoutTheme.CFWebCheckoutThemeBuilder()
          .setNavigationBarBackgroundColor("#6A3FD3")
          .setNavigationBarTextColor("#FFFFFF")
          .build();

      ```

      ```kotlin kotlin theme={"dark"}
      val cfTheme = CFWebCheckoutThemeBuilder()
          .setNavigationBarBackgroundColor("#000000")
          .setNavigationBarTextColor("#FFFFFF")
          .build()

      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="UPI Intent Checkout">
    <CodeGroup>
      ```java java theme={"dark"}
      CFIntentTheme cfTheme = new CFIntentTheme.CFIntentThemeBuilder()
          .setPrimaryTextColor("#000000")
          .setBackgroundColor("#FFFFFF")
          .build();

      ```

      ```kotlin kotlin theme={"dark"}
      val cfTheme = CFIntentThemeBuilder()
          .setPrimaryTextColor("#000000")
          .setBackgroundColor("#FFFFFF")
          .build()
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

#### Create checkout payment object

<AccordionGroup>
  <Accordion title="Web Checkout">
    This object combines all the configurations (session, theme) into a single checkout configuration. Finally, call `doPayment()` to open the Cashfree web checkout screen. This will present the user with the payment options and handle the payment process.

    <CodeGroup>
      ```java java theme={"dark"}
      CFWebCheckoutPayment cfWebCheckoutPayment = new CFWebCheckoutPayment.CFWebCheckoutPaymentBuilder()
          .setSession(cfSession)
          .setCFWebCheckoutUITheme(cfTheme)
          .build();
      ```

      ```kotlin kotlin theme={"dark"}
      val cfWebCheckoutPayment = CFWebCheckoutPaymentBuilder()
        .setSession(cfSession)
        .setCFWebCheckoutUITheme(cfTheme)
        .build()
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="UPI Intent Checkout">
    Use `CFUPIIntentCheckoutPayment` to create the payment object for UPI Intent flow. This object accepts a `CFSession` and theme configuration.

    <CodeGroup>
      ```java java theme={"dark"}
      CFUPIIntentCheckout cfupiIntentCheckout = new CFUPIIntentCheckout.CFUPIIntentBuilder()
              // Use either the enum or the application package names to order the UPI apps as per your needed
              // Remove both if you want to use the default order which cashfree provides based on the popularity
              // NOTE - only one is needed setOrder or setOrderUsingPackageName
              .setOrder(Arrays.asList(CFUPIIntentCheckout.CFUPIApps.BHIM, CFUPIIntentCheckout.CFUPIApps.PHONEPE))
              .setOrderUsingPackageName(Arrays.asList("com.dreamplug.androidapp", "in.org.npci.upiapp"))
              .build();

      CFUPIIntentCheckoutPayment cfupiIntentCheckoutPayment = new CFUPIIntentCheckoutPayment.CFUPIIntentPaymentBuilder()
              .setSession(cfSession)
              .setCfUPIIntentCheckout(cfupiIntentCheckout)
              .setCfIntentTheme(cfTheme)
              .build();
      ```

      ```kotlin kotlin theme={"dark"}
      val cfupiIntentCheckout = CFUPIIntentBuilder() // Use either the enum or the application package names to order the UPI apps as per your needed
              // Remove both if you want to use the default order which cashfree provides based on the popularity
              // NOTE - only one is needed setOrder or setOrderUsingPackageName
              .setOrderUsingPackageName(Arrays.asList("com.dreamplug.androidapp", "in.org.npci.upiapp"))
              .setOrder(Arrays.asList(CFUPIIntentCheckout.CFUPIApps.BHIM, CFUPIIntentCheckout.CFUPIApps.PHONEPE))
              .build()

      val cfupiIntentCheckoutPayment = CFUPIIntentPaymentBuilder()
              .setSession(cfSession)
              .setCfUPIIntentCheckout(cfupiIntentCheckout)
              .setCfIntentTheme(cfTheme)
              .build()
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

#### Set up payment callback

The SDK exposes an interface `CFCheckoutResponseCallback` to receive callbacks from the SDK once the payment journey ends.

This interface consists of 2 methods:

<CodeGroup>
  ```java java theme={"dark"}
  public void onPaymentVerify(String orderID)
  public void onPaymentFailure(CFErrorResponse cfErrorResponse, String orderID)
  ```

  ```kotlin kotlin theme={"dark"}
  fun onPaymentVerify(orderID: String)
  fun onPaymentFailure(cfErrorResponse: CFErrorResponse, orderID: String) 
  ```
</CodeGroup>

<Tip>Make sure to set the callback at activity's onCreate as this also handles the activity restart cases.</Tip>

<CodeGroup>
  ```java java theme={"dark"}
  public class YourActivity extends AppCompatActivity implements CFCheckoutResponseCallback {
      ...
      @Override
      public void onPaymentVerify(String orderID) {

      }

      @Override
      public void onPaymentFailure(CFErrorResponse cfErrorResponse, String orderID) {

      }

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_upi_intent_checkout);
          try {
            // If you are using a fragment then you need to add this line inside onCreate() of your Fragment
              CFPaymentGatewayService.getInstance().setCheckoutCallback(this);
          } catch (CFException e) {
              e.printStackTrace();
          }
      }
      ...

  }

  ```

  ```kotlin kotlin theme={"dark"}
  class YourActivity : AppCompatActivity(), CFCheckoutResponseCallback {

      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_drop_checkout)
          try {
              CFPaymentGatewayService.getInstance().setCheckoutCallback(this)
          } catch (e: CFException) {
              e.printStackTrace()
          }
      }

      override fun onPaymentVerify(orderID: String) {
          Log.d("onPaymentVerify", "verifyPayment triggered")
      }

      override fun onPaymentFailure(cfErrorResponse: CFErrorResponse, orderID: String) {
          Log.e("onPaymentFailure $orderID", cfErrorResponse.message)
      }
  ...
  }
  ```
</CodeGroup>

#### Initiate the payment

Finally, call `doPayment()` to open the Cashfree checkout screen. This will present the user with the payment options and handle the payment process.

<AccordionGroup>
  <Accordion title="Web Checkout">
    <CodeGroup>
      ```java java theme={"dark"}
      // replace the WebCheckoutActivity class with your class name
      CFPaymentGatewayService.getInstance().doPayment(WebCheckoutActivity.this, cfWebCheckoutPayment);
      ```

      ```kotlin kotlin theme={"dark"}
      // replace the WebCheckoutActivity class with your class name
      CFPaymentGatewayService.getInstance().doPayment(this@WebCheckoutActivity, cfWebCheckoutPayment)
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="UPI Intent Checkout">
    <CodeGroup>
      ```java java theme={"dark"}
      // replace the UPIIntentCheckoutActivity class with your class name
      CFPaymentGatewayService.getInstance().doPayment(UPIIntentCheckoutActivity.this, cfupiIntentCheckoutPayment);
      ```

      ```kotlin kotlin theme={"dark"}
      // replace the UPIIntentCheckoutActivity class with your class name
      CFPaymentGatewayService.getInstance().doPayment(this@UPIIntentCheckoutActivity, cfupiIntentCheckoutPayment)
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

#### Sample code

<AccordionGroup>
  <Accordion title="Web Checkout Sample code">
    <CodeGroup>
      ```java java theme={"dark"}
      package com.cashfree.sdk_sample;

      import android.content.Intent;
      import android.os.Bundle;
      import android.util.Log;

      import androidx.appcompat.app.AppCompatActivity;

      import com.cashfree.pg.api.CFPaymentGatewayService;
      import com.cashfree.pg.core.api.CFSession;
      import com.cashfree.pg.core.api.webcheckout.CFTheme;
      import com.cashfree.pg.core.api.callback.CFCheckoutResponseCallback;
      import com.cashfree.pg.core.api.exception.CFException;
      import com.cashfree.pg.core.api.utils.CFErrorResponse;
      import com.cashfree.pg.core.api.webcheckout.CFWebCheckoutPayment;
      import com.cashfree.pg.core.api.callback.CFCheckoutResponseCallback;

      public class WebCheckoutActivity extends AppCompatActivity implements CFCheckoutResponseCallback {

          String orderID = "ORDER_ID";
          String paymentSessionID = "TOKEN";
          CFSession.Environment cfEnvironment = CFSession.Environment.PRODUCTION;

          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_drop_checkout);
              try {
                  CFPaymentGatewayService.getInstance().setCheckoutCallback(this);
              } catch (CFException e) {
                  e.printStackTrace();
              }
          }

          @Override
          public void onPaymentVerify(String orderID) {
              Log.e("onPaymentVerify", "verifyPayment triggered");
             // Start verifying your payment
          }

          @Override
          public void onPaymentFailure(CFErrorResponse cfErrorResponse, String orderID) {
              Log.e("onPaymentFailure " + orderID, cfErrorResponse.getMessage());
          }

          public void doWebCheckoutPayment() {
              try {
                  CFSession cfSession = new CFSession.CFSessionBuilder()
                          .setEnvironment(cfEnvironment)
                          .setPaymentSessionID(paymentSessionID)
                          .setOrderId(orderID)
                          .build();
                  // Replace with your application's theme colors
                  CFWebCheckoutTheme cfTheme = new CFWebCheckoutTheme.CFWebCheckoutThemeBuilder()
                          .setNavigationBarBackgroundColor("#fc2678")
                          .setNavigationBarTextColor("#ffffff")
                          .build();
                  CFWebCheckoutPayment cfWebCheckoutPayment = new CFWebCheckoutPayment.CFWebCheckoutPaymentBuilder()
                          .setSession(cfSession)
                          .setCFWebCheckoutUITheme(cfTheme)
                          .build();
                  CFPaymentGatewayService.getInstance().doPayment(WebCheckoutActivity.this, cfWebCheckoutPayment);
              } catch (CFException exception) {
                  exception.printStackTrace();
              }
          }

      }
      ```

      ```kotlin kotlin theme={"dark"}

      package com.cashfree.sdk_sample.kotlin

      import androidx.appcompat.app.AppCompatActivity
      import com.cashfree.pg.core.api.callback.CFCheckoutResponseCallback
      import com.cashfree.pg.core.api.CFSession
      import android.os.Bundle
      import com.cashfree.sdk_sample.R
      import com.cashfree.pg.api.CFPaymentGatewayService
      import android.content.Intent
      import android.app.Activity
      import com.cashfree.pg.core.api.utils.CFErrorResponse
      import android.text.TextUtils
      import android.util.Log
      import android.widget.Toast
      import com.cashfree.pg.core.api.CFSession.CFSessionBuilder
      import com.cashfree.pg.core.api.exception.CFException
      import com.cashfree.pg.core.api.webcheckout.CFWebCheckoutTheme
      import com.cashfree.pg.core.api.webcheckout.CFWebCheckoutTheme.CFWebCheckoutThemeBuilder
      import com.cashfree.pg.core.api.webcheckout.CFWebCheckoutPayment
      import com.cashfree.pg.core.api.webcheckout.CFWebCheckoutPayment.CFWebCheckoutPaymentBuilder

      class WebCheckoutActivity : AppCompatActivity(), CFCheckoutResponseCallback { var orderID = "ORDER_ID" var paymentSessionID = "PAYMENT_SESSION_ID" var cfEnvironment = CFSession.Environment.PRODUCTION override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_drop_checkout) try { CFPaymentGatewayService.getInstance().setCheckoutCallback(this) } catch (e: CFException) { e.printStackTrace() } }

          var cfEnvironment = CFSession.Environment.SANDBOX
          override fun onPaymentVerify(orderID: String) {
              Log.d("onPaymentVerify", "verifyPayment triggered")
          }

          override fun onPaymentFailure(cfErrorResponse: CFErrorResponse, orderID: String) {
              Log.e("onPaymentFailure $orderID", cfErrorResponse.message)
          }

          fun doWebCheckoutPayment() {
              try {
                  val cfSession = CFSessionBuilder()
                      .setEnvironment(cfEnvironment)
                      .setPaymentSessionID(paymentSessionID)
                      .setOrderId(orderID)
                      .build()
                  val cfTheme = CFWebCheckoutThemeBuilder()
                      .setNavigationBarBackgroundColor("#000000")
                      .setNavigationBarTextColor("#FFFFFF")
                      .build()
                  val cfWebCheckoutPayment = CFWebCheckoutPaymentBuilder()
                      .setSession(cfSession)
                      .setCFWebCheckoutUITheme(cfTheme)
                      .build()
                  CFPaymentGatewayService.getInstance().doPayment(this@WebCheckoutActivity, cfWebCheckoutPayment)
              } catch (exception: CFException) {
                  exception.printStackTrace()
              }
          }

      } 
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="UPI Intent Checkout Sample code">
    <CodeGroup>
      ```java java theme={"dark"}
      package com.cashfree.sdk_sample;

      import android.content.Intent;
      import android.os.Bundle;
      import android.util.Log;

      import androidx.appcompat.app.AppCompatActivity;

      import com.cashfree.pg.api.CFPaymentGatewayService;
      import com.cashfree.pg.core.api.CFSession;
      import com.cashfree.pg.core.api.CFTheme;
      import com.cashfree.pg.core.api.callback.CFCheckoutResponseCallback;
      import com.cashfree.pg.core.api.exception.CFException;
      import com.cashfree.pg.core.api.utils.CFErrorResponse;
      import com.cashfree.pg.ui.api.upi.intent.CFIntentTheme;
      import com.cashfree.pg.ui.api.upi.intent.CFUPIIntentCheckout;
      import com.cashfree.pg.ui.api.upi.intent.CFUPIIntentCheckoutPayment;

      public class UPIIntentCheckoutActivity extends AppCompatActivity implements CFCheckoutResponseCallback {

          String orderID = "ORDER_ID";
          String paymentSessionID = "PAYMENT_SESSION_ID";
          CFSession.Environment cfEnvironment = CFSession.Environment.SANDBOX;

          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_upi_intent_checkout);
              try {
                  CFPaymentGatewayService.getInstance().setCheckoutCallback(this);
              } catch (CFException e) {
                  e.printStackTrace();
              }
          }

          @Override
          public void onPaymentVerify(String orderID) {
              Log.e("onPaymentVerify", "verifyPayment triggered");
              // Start verifying your payment
          }

          @Override
          public void onPaymentFailure(CFErrorResponse cfErrorResponse, String orderID) {
              Log.e("onPaymentFailure " + orderID, cfErrorResponse.getMessage());
          }

          public void doUPIIntentCheckoutPayment() {
              try {
                  CFSession cfSession = new CFSession.CFSessionBuilder()
                          .setEnvironment(cfEnvironment)
                          .setOrderToken(token)
                          .setOrderId(orderID)
                          .build();
                  // Replace with your application's theme colors
                  CFIntentTheme cfTheme = new CFIntentTheme.CFIntentThemeBuilder()
                          .setButtonBackgroundColor("#6A3FD3")
                          .setButtonTextColor("#FFFFFF")
                          .setPrimaryTextColor("#000000")
                          .setSecondaryTextColor("#000000")
                          .build();

                  CFUPIIntentCheckout cfupiIntentCheckout = new CFUPIIntentCheckout.CFUPIIntentBuilder()
                          // Use either the enum or the application package names to order the UPI apps as per your needed
                          // Remove both if you want to use the default order which cashfree provides based on the popularity
                          // NOTE - only one is needed setOrder or setOrderUsingPackageName
                          .setOrder(Arrays.asList(CFUPIIntentCheckout.CFUPIApps.BHIM, CFUPIIntentCheckout.CFUPIApps.PHONEPE))
                          .setOrderUsingPackageName(Arrays.asList("com.dreamplug.androidapp", "in.org.npci.upiapp"))
                          .build();

                  CFUPIIntentCheckoutPayment cfupiIntentCheckoutPayment = new CFUPIIntentCheckoutPayment.CFUPIIntentPaymentBuilder()
                          .setSession(cfSession)
                          .setCfUPIIntentCheckout(cfupiIntentCheckout)
                          .setCfIntentTheme(cfTheme)
                          .build();
                  CFPaymentGatewayService.getInstance().doPayment(UPIIntentCheckoutActivity.this, cfupiIntentCheckoutPayment);
              } catch (CFException exception) {
                  exception.printStackTrace();
              }
          }

      }
      ```

      ```kotlin kotlin theme={"dark"}
      package com.cashfree.sdk_sample.kotlin

      import androidx.appcompat.app.AppCompatActivity
      import com.cashfree.pg.core.api.callback.CFCheckoutResponseCallback
      import com.cashfree.pg.core.api.CFSession
      import android.os.Bundle
      import com.cashfree.sdk_sample.R
      import com.cashfree.pg.api.CFPaymentGatewayService
      import android.content.Intent
      import android.app.Activity
      import com.cashfree.pg.core.api.utils.CFErrorResponse
      import android.text.TextUtils
      import android.util.Log
      import android.widget.Toast
      import com.cashfree.pg.core.api.CFSession.CFSessionBuilder
      import com.cashfree.pg.core.api.exception.CFException
      import com.cashfree.pg.ui.api.upi.intent.CFIntentTheme
      import com.cashfree.pg.ui.api.upi.intent.CFIntentTheme.CFIntentThemeBuilder
      import com.cashfree.pg.ui.api.upi.intent.CFUPIIntentCheckout
      import com.cashfree.pg.ui.api.upi.intent.CFUPIIntentCheckout.CFUPIIntentBuilder
      import com.cashfree.pg.ui.api.upi.intent.CFUPIIntentCheckoutPayment
      import com.cashfree.pg.ui.api.upi.intent.CFUPIIntentCheckoutPayment.CFUPIIntentPaymentBuilder

      class UPIIntentCheckoutActivity : AppCompatActivity(), CFCheckoutResponseCallback {
          var orderID = "ORDER_ID"
          var token = "TOKEN"
          var cfEnvironment = CFSession.Environment.SANDBOX
          override fun onCreate(savedInstanceState: Bundle?) {
              super.onCreate(savedInstanceState)
              setContentView(R.layout.activity_drop_checkout)
              try {
                  CFPaymentGatewayService.getInstance().setCheckoutCallback(this)
                  doDropCheckoutPayment()
              } catch (e: CFException) {
                  e.printStackTrace()
              }
          }

          override fun onPaymentVerify(orderID: String) {
              Log.d("onPaymentVerify", "verifyPayment triggered")
          }

          override fun onPaymentFailure(cfErrorResponse: CFErrorResponse, orderID: String) {
              Log.e("onPaymentFailure $orderID", cfErrorResponse.message)
          }

          fun doUPIIntentCheckoutPayment() {
              try {
                  val cfSession = CFSessionBuilder()
                      .setEnvironment(cfEnvironment)
                      .setPaymentSessionID(token)
                      .setOrderId(orderID)
                      .build()
                  val cfTheme = CFIntentThemeBuilder()
                      .setPrimaryTextColor("#000000")
                      .setBackgroundColor("#FFFFFF")
                      .build()
                  val cfupiIntentCheckout = CFUPIIntentBuilder() 
                      // Use either the enum or the application package names to order the UPI apps as per your needed
                      // Remove both if you want to use the default order which cashfree provides based on the popularity
                      // NOTE - only one is needed setOrder or setOrderUsingPackageName
                      .setOrderUsingPackageName(Arrays.asList("com.dreamplug.androidapp", "in.org.npci.upiapp"))
                      .setOrder(Arrays.asList(CFUPIIntentCheckout.CFUPIApps.BHIM, CFUPIIntentCheckout.CFUPIApps.PHONEPE))
                      .build()
                  val cfupiIntentCheckoutPayment = CFUPIIntentPaymentBuilder()
                      .setSession(cfSession)
                      .setCfUPIIntentCheckout(cfupiIntentCheckout)
                      .setCfIntentTheme(cfTheme)
                      .build()
                  CFPaymentGatewayService.getInstance().doPayment(this@UPIIntentActivity, cfupiIntentCheckoutPayment)
              } catch (exception: CFException) {
                  exception.printStackTrace()
              }
          }
      }
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>

#### Sample GitHub code

<AccordionGroup>
  <Accordion title="Android Integration">
    [GitHub Sample](https://github.com/cashfree/nextgen-android)
  </Accordion>
</AccordionGroup>

## Step 3: Confirm the payment <Badge color="green">Server-side</Badge>

After the customer completes the payment, you must confirm the payment status. Once the payment finishes, the user redirects back to your activity.

To verify an order you can call our `/pg/orders` endpoint from your backend. You can also use our SDK to achieve the same.

<CodeGroup>
  ```go golang theme={"dark"}
  version := "2023-08-01"
  response, httpResponse, err := cashfree.PGFetchOrder(&version, "<order_id>", nil, nil, nil)
  if err != nil {
  	fmt.Println(err.Error())
  } else {
  	fmt.Println(httpResponse.StatusCode)
  	fmt.Println(response)
  }
  ```

  ```javascript javascript theme={"dark"}
  cashfree
  	.PGFetchOrder("<order_id>")
  	.then((response) => {
  		console.log("Order fetched successfully:", response.data);
  	})
  	.catch((error) => {
  		console.error("Error:", error.response.data.message);
  	});
  ```

  ```php php theme={"dark"}
  $x_api_version = "2023-08-01";
  try {
      $response = $cashfree->PGFetchOrder($x_api_version, "<order_id>");
      print_r($response);
  } catch (Exception $e) {
      echo 'Exception when calling PGFetchOrder: ', $e->getMessage(), PHP_EOL;
  }
  ```

  ```java java theme={"dark"}
  import com.cashfree.*;
  //other code

  try {
      Cashfree.XClientId = "<x-client-id>";
      Cashfree.XClientSecret = "<x-client-secret>";
      Cashfree.XEnvironment = Cashfree.SANDBOX;

      Cashfree cashfree = new Cashfree();
      String xApiVersion = "2023-08-01";

      ApiResponse<OrderEntity> responseFetchOrder = cashfree.PGFetchOrder(xApiVersion, "<order_id>", null, null, null);
      System.out.println(response.getData().getOrderId());
  } catch (ApiException e) {
      throw new RuntimeException(e);
  }
  ```

  ```python python theme={"dark"}
  from cashfree_pg.models.create_order_request import CreateOrderRequest
  from cashfree_pg.api_client import Cashfree
  from cashfree_pg.models.customer_details import CustomerDetails
  from cashfree_pg.models.order_meta import OrderMeta

  Cashfree.XClientId = "<x-client-id>"
  Cashfree.XClientSecret = "<x-client-secret>"
  Cashfree.XEnvironment = Cashfree.SANDBOX
  x_api_version = "2023-08-01"

  try:
      api_response = Cashfree().PGFetchOrder(x_api_version, "order_3242X4jQ5f0S9KYxZO9mtDL1Kx2Y7u", None)
      print(api_response.data)
  except Exception as e:
      print(e)

  ```

  ```csharp csharp theme={"dark"}
  using cashfree_pg.Client;
  using cashfree_pg.Model;

  Cashfree.XClientId = "<x-client-id>";
  Cashfree.XClientSecret = "<x-client-secret>";
  Cashfree.XEnvironment = Cashfree.SANDBOX;
  var cashfree = new Cashfree();
  var xApiVersion = "2023-08-01";

  try {
      var result = cashfree.PGFetchOrder(xApiVersion, "<order_id>>", null, null);
      Console.WriteLine(result);
      Console.WriteLine(result.StatusCode);
      Console.WriteLine((result.Content as OrderEntity));
  } catch (ApiException e) {
      Console.WriteLine("Exception when calling PGFetchOrder: " + e.Message);
      Console.WriteLine("Status Code: " + e.ErrorCode);
      Console.WriteLine(e.StackTrace);
  }
  ```

  ```bash curl theme={"dark"}
  curl --request GET \
       --url https://sandbox.cashfree.com/pg/orders/{order_id} \
       --header 'accept: application/json' \
       --header 'x-api-version: 2025-01-01'
       --header 'x-client-id: "YOUR APP ID GOES HERE"'
       --header 'x-client-secret: "YOUR SECRET KEY GOES HERE'
  ```
</CodeGroup>

<Note>
  Always verify the order status before you deliver services to the customer. You can use the [Get Order API](/api-reference/payments/latest/orders/get) for this. An order is successful when the `order_status` is `PAID`.
</Note>

## Testing

After you integrate the checkout functionality, verify that it opens the Cashfree-hosted payment page. Follow these steps to test:

1. Click the checkout button.
2. Verify you're redirected to the Cashfree Checkout payment page.

## Error codes

To confirm the error returned in your Android application, you can view the error codes that are exposed by the SDK.

<Accordion title="Show error codes">
  | Error codes                    | Message                                                                                                                                                             |
  | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | MISSING\_CALLBACK              | The callback is missing in the request.                                                                                                                             |
  | ORDER\_ID\_MISSING             | The "order\_id" is missing in the request.                                                                                                                          |
  | CARD\_EMI\_TENURE\_MISSING     | The "emi\_tenure" is missing or invalid (It has to be greater than 0).                                                                                              |
  | INVALID\_UPI\_APP\_ID\_SENT    | The id sent is invalid. The value has to be one of the following: "tez://","phonepe://","paytm://","bhim://. Please refer the note in CFUPI class for more details" |
  | INVALID\_PAYMENT\_OBJECT\_SENT | The payment object that's set doesn't match any payment mode. Please set the correct payment mode and try again.                                                    |
  | WALLET\_OBJECT\_MISSING        | The CFWallet object is missing in the request                                                                                                                       |
  | NETBANKING\_OBJECT\_MISSING    | The CFNetbanking object is missing in the request.                                                                                                                  |
  | UPI\_OBJECT\_MISSING           | The CFUPI object is missing in the request.                                                                                                                         |
  | CARD\_OBJECT\_MISSING          | The CFCard object is missing in the request.                                                                                                                        |
  | INVALID\_WEB\_DATA             | The url seems to be corrupt. Please reinstantiate the order.                                                                                                        |
  | SESSION\_OBJECT\_MISSING       | The "session" is missing in the request                                                                                                                             |
  | PAYMENT\_OBJECT\_MISSING       | The "payment" is missing in the request                                                                                                                             |
  | ENVIRONMENT\_MISSING           | The "environment" is missing in the request.                                                                                                                        |
  | ORDER\_TOKEN\_MISSING          | The "order\_token" is missing in the request.                                                                                                                       |
  | CHANNEL\_MISSING               | The "channel" is missing in the request.                                                                                                                            |
  | CARD\_NUMBER\_MISSING          | The "card\_number" is missing in the request.                                                                                                                       |
  | CARD\_EXPIRY\_MONTH\_MISSING   | The "card\_expiry\_mm" is missing in the request.                                                                                                                   |
  | CARD\_EXPIRY\_YEAR\_MISSING    | The "card\_expiry\_yy" is missing in the request.                                                                                                                   |
  | CARD\_CVV\_MISSING             | The "card\_cvv" is missing in the request.                                                                                                                          |
  | UPI\_ID\_MISSING               | The "upi\_id" is missing in the request                                                                                                                             |
  | WALLET\_CHANNEL\_MISSING       | The "channel" is missing in the wallet payment request                                                                                                              |
  | WALLET\_PHONE\_MISSING         | The "phone number" is missing in the wallet payment request                                                                                                         |
  | NB\_BANK\_CODE\_MISSING        | The "bank\_code" is missing in the request                                                                                                                          |
  | WRONG\_CALLING\_CONTEXT        | Calling context must be activity or fragment                                                                                                                        |
  | NO\_UPI\_APP\_AVAILABLE        | You don't have any UPI apps installed or ready for payment.                                                                                                         |
  | NO\_EMI\_PLAN\_AVAILABLE       | This account doesn't have EMI plans configured, or the order amount is less than 2499                                                                               |
</Accordion>

### Other options

<AccordionGroup>
  <Accordion title="(Optional) Custom Initialisation of the SDK">
    If you require to initialise the SDK yourself then follow the steps below. Make sure to initialise the SDK in Application class to avoid any Runtime issues.

    <Steps>
      <Step title="Add the following to your values.xml file">
        `<bool name="cashfree_pg_core_auto_initialize_enabled">false</bool>`
      </Step>

      <Step title="Initialise the SDK yourself before attempting payment">
        <CodeGroup>
          ```java java theme={"dark"}
             Executors.newSingleThreadExecutor().execute(() -> { 
                  CFPaymentGatewayService.initialize(getApplicationContext());
             });
          ```

          ```kotlin kotlin theme={"dark"}
             Executors.newSingleThreadExecutor().execute {
                CFPaymentGatewayService.initialize(applicationContext)
             }
          ```
        </CodeGroup>
      </Step>
    </Steps>
  </Accordion>

  <Accordion title="(Optional) Enable logging to debugging issues">
    To enable SDK logging add the following to your `values.xml` file.

    `<integer name="cashfree_pg_logging_level">3</integer>`

    Following are the Logging levels.

    * VERBOSE = 2
    * DEBUG = 3
    * INFO = 4
    * WARN = 5
    * ERROR = 6
    * ASSERT = 7
  </Accordion>

  <Accordion title="(Optional) Disable Quick Checkout in Payment Page">
    If you want to disable quick checkout flow in the payment journey you can add the following to your values.xml file.

    `<bool name="cf_quick_checkout_enabled">false</bool>`
  </Accordion>

  <Accordion title="(Optional) Disable Encrypted SharedPreference">
    Add the following to your values.xml file.

    `<bool name="cashfree_pg_core_encrypt_pref_enabled">false</bool>`
  </Accordion>
</AccordionGroup>

<div
  className="callout info"
  style={{
backgroundColor: 'light-dark(#f9f7fd, #2d1b4e)',
borderColor: 'light-dark(#cdbaef, #6930ca)',
color: 'light-dark(#000000, #ffffff)'
}}
>
  <p style={{fontSize: '1.3em', fontWeight: '500', marginBottom: '16px'}}>Affiliate partner program</p>

  <p>As a developer building payment experiences for your clients, you can earn additional income while providing them with industry-leading payment solutions.</p>

  <p>Join the <a href="https://partner.cashfree.com/partner-ui/authentication/signup?source-action=Affiliate%20Program%20LP&action=Sign%20Up&button-id=StartNow_CashfreeAffiliatePartnerProgram">Cashfree affiliate partner program</a> and get rewarded every time your clients use Cashfree.</p>

  <p>**What you get:**</p>

  <ul>
    <li>Earn up to 0.25% commission on every transaction.</li>
    <li>Become a trusted fintech partner for your clients.</li>
    <li>Access to a dedicated partner manager for expert support.</li>
  </ul>

  <p>**What your clients get:**</p>

  <ul>
    <li>Instant activation and go live in minutes.</li>
    <li>Industry-best success rate across all payment modes.</li>
    <li>Effortless acceptance of international payments in 140+ currencies.</li>
  </ul>

  <p>Get started today. <a href="https://partner.cashfree.com/partner-ui/authentication/signup?source-action=Affiliate%20Program%20LP&action=Sign%20Up&button-id=StartNow_BecomeAPartner">Become a partner now</a>.</p>
</div>

<div class="hidden" data-table-of-contents="bottom">
  <p class="mt-4 font-medium flex items-center gap-2 related-docs-heading">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class="w-4 h-4">
      <path d="M3 4h7a2 2 0 0 1 2 2v13a2 2 0 0 0-2-2H3z" />

      <path d="M21 4h-7a2 2 0 0 0-2 2v13a2 2 0 0 1 2-2h7z" />
    </svg>

    <span>Related topics</span>
  </p>

  <ul>
    <li><a href="/docs/api-reference/payments/latest/orders/create">Create Order API</a></li>
    <li><a href="/docs/api-reference/payments/sdk#payment-sdk">Payment SDK API Overview</a></li>
    <li><a href="https://github.com/cashfree/nextgen-android" target="_blank">Android SDK on GitHub</a></li>
  </ul>
</div>
