Skip to main content
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: The Android integration consists of three essential steps: The step-by-step guide for each step of the integration process is as follows:

Step 1: Create an order Server-side

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.
Create orders through your server as this API requires your secret key. Don’t call it directly from your mobile application.
API request for creating an order
Here’s a sample request for creating an order using your desired backend language. Cashfree offers backend SDKs to simplify the integration process.
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);
		});
}
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.

Step 2: Open the checkout page Client-side

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 in Maven Central. You can download the latest version here. The Android SDK supports Android SDK version 19 and above. Add the following dependency to your app’s build.gradle file:
implementation 'com.cashfree.pg:api:2.2.9'

2. Select a payment flow

The Android SDK offers the following payment flows:
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.
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.

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).
CFSession cfSession = new CFSession.CFSessionBuilder()
        .setEnvironment(CFSession.Environment.SANDBOX)
        .setPaymentSessionID("paymentSessionID")
        .setOrderId("orderID")
        .build();

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.
CFWebCheckoutTheme cfTheme = new CFWebCheckoutTheme.CFWebCheckoutThemeBuilder()
    .setNavigationBarBackgroundColor("#6A3FD3")
    .setNavigationBarTextColor("#FFFFFF")
    .build();

CFIntentTheme cfTheme = new CFIntentTheme.CFIntentThemeBuilder()
    .setPrimaryTextColor("#000000")
    .setBackgroundColor("#FFFFFF")
    .build();

Create checkout payment object

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.
CFWebCheckoutPayment cfWebCheckoutPayment = new CFWebCheckoutPayment.CFWebCheckoutPaymentBuilder()
    .setSession(cfSession)
    .setCFWebCheckoutUITheme(cfTheme)
    .build();
Use CFUPIIntentCheckoutPayment to create the payment object for UPI Intent flow. This object accepts a CFSession and theme configuration.
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();

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:
public void onPaymentVerify(String orderID)
public void onPaymentFailure(CFErrorResponse cfErrorResponse, String orderID)
Make sure to set the callback at activity’s onCreate as this also handles the activity restart cases.
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();
        }
    }
    ...

}

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.
// replace the WebCheckoutActivity class with your class name
CFPaymentGatewayService.getInstance().doPayment(WebCheckoutActivity.this, cfWebCheckoutPayment);
// replace the UPIIntentCheckoutActivity class with your class name
CFPaymentGatewayService.getInstance().doPayment(UPIIntentCheckoutActivity.this, cfupiIntentCheckoutPayment);

Sample code

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();
        }
    }

}
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();
        }
    }

}

Sample GitHub code

Step 3: Confirm the payment Server-side

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.
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)
}
Always verify the order status before you deliver services to the customer. You can use the Get Order API for this. An order is successful when the order_status is PAID.

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.
Error codesMessage
MISSING_CALLBACKThe callback is missing in the request.
ORDER_ID_MISSINGThe “order_id” is missing in the request.
CARD_EMI_TENURE_MISSINGThe “emi_tenure” is missing or invalid (It has to be greater than 0).
INVALID_UPI_APP_ID_SENTThe 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_SENTThe payment object that’s set doesn’t match any payment mode. Please set the correct payment mode and try again.
WALLET_OBJECT_MISSINGThe CFWallet object is missing in the request
NETBANKING_OBJECT_MISSINGThe CFNetbanking object is missing in the request.
UPI_OBJECT_MISSINGThe CFUPI object is missing in the request.
CARD_OBJECT_MISSINGThe CFCard object is missing in the request.
INVALID_WEB_DATAThe url seems to be corrupt. Please reinstantiate the order.
SESSION_OBJECT_MISSINGThe “session” is missing in the request
PAYMENT_OBJECT_MISSINGThe “payment” is missing in the request
ENVIRONMENT_MISSINGThe “environment” is missing in the request.
ORDER_TOKEN_MISSINGThe “order_token” is missing in the request.
CHANNEL_MISSINGThe “channel” is missing in the request.
CARD_NUMBER_MISSINGThe “card_number” is missing in the request.
CARD_EXPIRY_MONTH_MISSINGThe “card_expiry_mm” is missing in the request.
CARD_EXPIRY_YEAR_MISSINGThe “card_expiry_yy” is missing in the request.
CARD_CVV_MISSINGThe “card_cvv” is missing in the request.
UPI_ID_MISSINGThe “upi_id” is missing in the request
WALLET_CHANNEL_MISSINGThe “channel” is missing in the wallet payment request
WALLET_PHONE_MISSINGThe “phone number” is missing in the wallet payment request
NB_BANK_CODE_MISSINGThe “bank_code” is missing in the request
WRONG_CALLING_CONTEXTCalling context must be activity or fragment
NO_UPI_APP_AVAILABLEYou don’t have any UPI apps installed or ready for payment.
NO_EMI_PLAN_AVAILABLEThis account doesn’t have EMI plans configured, or the order amount is less than 2499

Other options

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

Add the following to your values.xml file

<bool name="cashfree_pg_core_auto_initialize_enabled">false</bool>
2

Initialize the SDK yourself before attempting payment

   Executors.newSingleThreadExecutor().execute(() -> { 
        CFPaymentGatewayService.initialize(getApplicationContext());
   });
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
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>
Add the following to your values.xml file.<bool name="cashfree_pg_core_encrypt_pref_enabled">false</bool>

Affiliate partner program

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

Join the Cashfree affiliate partner program and get rewarded every time your clients use Cashfree.

What you get:

  • Earn up to 0.25% commission on every transaction.
  • Become a trusted fintech partner for your clients.
  • Access to a dedicated partner manager for expert support.

What your clients get:

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

Get started today. Become a partner now.