3.2 Initiate Payment - Element Checkout

Cashfree payment gateway's Android SDK (supports Android SDK version 19 and above) provides a way for users who want to implement the payment screen as per their requirement and then use our SDK to process the payment.

Customer selects the payment mode and enters payment details inside the merchant's application. These details are then passed on to the our Android SDK for processing. Once the payment is initiated, the SDK informs about the payment events using callback functions (payment verification, failure etc).

11981198

Element Checkout flow

📘

Here you can find the sample application demonstrating the usage of this SDK

Initiate the payment by following these steps

  1. Create a CFSession object.
  2. Create a payment mode object (CFCard, CFWallet, CFUPI, etc.) for the selected payment mode and setup the callbacks.
  3. Create the payment object (CFCardPayment, CFWalletPayment, etc.) for the selected payment mode.
  4. Set payment callback.
  5. Initiate the payment using the payment object created from [step 3]

Create a session

As discussed above, the payment_session_id contains all the order details and is used to authenticate the payment. The SDK exposes a class CFSession which has member variables for a payment session. One of them sets the payment_session_id value.

Cashfree provides the following two environments for our merchants

  1. Sandbox environment for developers to test the payment flow and responses
  2. Production environment for live transactions.

The values for environment field can be either .SANDBOX or .PRODUCTION.

Code Snippet

try {
    CFSession cfSession = new CFSession.CFSessionBuilder()
        .setEnvironment(CFSession.Environment.PRODUCTION) //Enum
        .setPaymentSessionID("Payment Session ID")
        .setOrderId("order1234")
        .build();
} catch (CFException exception) {
    exception.printStackTrace();
}

Create a payment mode objects

Our Android SDK provides multiple modes to make payment. You can choose any mode depending on the requirement and invoke that payment mode from the SDK.

The following payment modes are supported by the Android SDK:-

  1. Card
  2. Netbanking
  3. UPI Collect
  4. UPI Intent
  5. Wallet
  6. EMI
  7. Paylater

Create a Card Object

  • A card object has to be created by sending all the required details i.e., Card Holder Name, Card Number, Card CVV and more
  • The SDK exposes a class CFCard that collects these details.
  • The below code snippet creates an object of CFCard
CFCard cfCard = new CFCard.CFCardBuilder()
                    .setCardHolderName(cardHolderName)
                    .setCardNumber(cardNumber)
                    .setCardExpiryMonth(cardMM)
                    .setCardExpiryYear(cardYY)
                    .setCVV(cardCVV)
                    .build();
  • To save a card, while making card payments please refer to this section

Create a Netbanking Object

  • A Netbanking object has to be created by sending all the required details i.e., Bank Code
  • The SDK exposes a class CFNetbanking that collects these details.
  • The below code snippet creates an object of CFNetbanking
CFNetBanking cfNetBanking = new CFNetBanking.CFNetBankingBuilder()
                        .setBankCode(bankCode)
                        .build();

📘

Visit to get a list of all the bank codes.

Create a Wallet Object

  • A Wallet object has to be created by sending all the required details i.e., provider name, phone number
  • The SDK exposes a class CFWallet that collects these details.
CFWallet cfWallet = new CFWallet.CFWalletBuilder()
                        .setProvider(channel)
                        .setPhone(phone)
                        .build();

Note: Below is the list of all values for all the wallet providers supported by Cashfree:-

  1. phonepe
  2. paytm
  3. amazon
  4. airtel
  5. freecharge
  6. mobikwik
  7. jio
  8. ola

Create a UPI Object

  • A UPI object has to be created by sending all the required details i.e., channel and UPI ID
  • The SDK exposes a class CFUPI that collects these details.
  • Cashfree provides 2 modes of payment with UPI. One being the collect flow and the other being the intent flow.
  • In the collect flow, the user has to enter his/her UPI ID and a request will be sent to that UPI ID to complete the payment.
  • In the intent flow, the user has to be presented with a list of all installed UPI applications present in the phone. Clicking on one of them, the user will be redirected to the application to complete the payment
  • Depending on the requirement, you can choose to use any.

The code snippet for CFUPI collect object.

CFUPI cfupi = new CFUPI.CFUPIBuilder()
                    .setMode(CFUPI.Mode.COLLECT)
                    .setUPIID("[email protected]")
                    .build();

Pre-requisite for UPI Intent

Android Manifest Change

If the project's targetSdkVersion is 30, add the following code to the android manifest file.

<manifest ...>

    <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="upi" android:host="pay"/>
        </intent>
        <package android:name="com.android.chrome" />
    </queries>
  ...
</manifest>

The code snippet CFUPI intent object

CFUPI cfupi = new CFUPI.CFUPIBuilder()
                    .setMode(CFUPI.Mode.INTENT)
                    .setUPIID("upi-app-id") //getUPIID using CFUPIUtil.getInstalledUPIApps()
                    .build();

Get UPI Apps and UPI ID

To Get the List of UPI Apps Installed in user's device you can use the following Utility function.

import com.cashfree.pg.core.api.utils.CFUPIUtil.*;
import com.cashfree.pg.core.api.utils.CFUPIApp;

CFUPIUtil.getInstalledUPIApps(this, upiAppsList -> {
  for (CFUPIApp cfUPIApp: upiAppsList) {
                cfUPIApp.getAppId(); // this is UPIID for CFUPI.CFUPIBuilder()
                cfUPIApp.getDisplayName(); // This is the name of the app to be shown on UI.
                cfUPIApp.getBase64Icon(); // this is the app icon encoded in base 64. 
                //  you can use it using the following code snippet.
                                //  byte[] imageBytes = Base64.decode(cfUPIApp.getDisplayName(), Base64.NO_WRAP);
                                //  Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                                //  yourImageView.setImageBitmap(decodedImage);
  }
});

Create a EMICard Object

  • An EMI card object has to be created by sending all the required details i.e., Card Holder Name, Card Number, Card CVV, EMI tenure and more
  • The SDK exposes a class CFEMICard that collects these details.
  • The below code snippet creates an object of CFEMICard
CFEMICard cfCard = new CFEMICard.CFEMICardBuilder()
                        .setCardHolderName("Name")
                        .setCardNumber("1234123412341234")
                        .setCardExpiryMonth("MM")
                        .setCardExpiryYear("YY")
                        .setCVV("123")
                        .setBankName("ICICI")
                        .setEMITenure(3)
                        .build();
AttributeSupported values
BankNameHolds Bank Name for the corresponding card. Values can be HDFC ICICI Kotak RBL BOB Standard Chartered
EMITenureHolds Tenure for the EMI payment.
Values are:
HDFC: 3 6 9 12
ICICI: 3 6 9 12
Kotak: 3 6 9 12 18 20 24 30 36
RBL: 3 6 9 12 18 24
BOB: 3 6 9 12 18 24 36
Standard Chartered: 3 6 9 12

Create a Paylater Object

  • A Paylater object has to be created by sending all the required details i.e., provider name, phone number
  • The SDK exposes a class CFPaylater that collects these details.
  • The below code snippet creates an object of CFPaylater
CFPayLater cfPayLater = new CFPayLater.CFPayLaterBuilder()
                        .setProvider(payLaterChannel)
                        .setPhone(phone)
                        .build();

Create the payment object

1. CFCardPayment

  • Code Snippet to create a payment object for card
CFCardPayment cfCardPayment = new CFCardPayment.CFCardPaymentBuilder()
                    .setSession(cfSession)
                    .setCard(cfCard)
                    .build();
  • Code Snippet to create a payment object for saving the card
CFCardPayment cfCardPayment = new CFCardPayment.CFCardPaymentBuilder()
                    .setSession(cfSession)
                    .setCard(cfCard)
                    .setSaveCardDetail(true)
                    .build();

2. CFNetbankingPayment

  • Code Snippet to create a payment object for netbanking
CFNetBankingPayment cfNetBankingPayment = new CFNetBankingPayment.CFNetBankingPaymentBuilder()
                        .setSession(cfSession)
                        .setCfNetBanking(cfNetBanking)
                        .build();

3. CFWalletPayment

  • Code Snippet to create a payment object for wallet
CFWalletPayment cfWalletPayment = new CFWalletPayment.CFWalletPaymentBuilder()
                        .setSession(cfSession)
                        .setCfWallet(cfWallet)
                        .build();

4. CFUPIPayment

  • Code Snippet to create a payment object for UPI
CFUPIPayment cfupiPayment = new CFUPIPayment.CFUPIPaymentBuilder()
                    .setSession(cfSession)
                    .setCfUPI(cfupi)
                    .build();

5. CFEMICardPayment

  • Code Snippet to create a payment object for EMI
CFEMICardPayment cfCardPayment = new CFEMICardPayment.CFEMICardPaymentBuilder()
                        .setSession(cfSession)
                        .setCard(cfCard)
                        .build();

6. CFPaylaterPayment

  • Code Snippet to create a payment object for card
CFPayLaterPayment cfPayLaterPayment = new CFPayLaterPayment.CFPayLaterPaymentBuilder()
                  .setSession(cfSession)
                  .setCfPayLater(cfPayLater)
                  .build();

Setup Payment Callback

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

This interface comprises of 2 methods:

  1. public void onPaymentVerify(String orderID)
  2. public void onPaymentFailure(CFErrorResponse cfErrorResponse, String orderID)
  • Code snippet demonstrating it's usage:
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_drop_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();
        }
    }
    ...
}

🚧

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

Initiate payment

  • Finally to initiate the payment, the above created Payment Object has to be sent to the SDK.
  • The SDK exposes a class CFPaymentGatewayService, which can be used to set the Payment Object and initiate the payment.
  • The below code snippet is an example demonstrating it's usage:
CFCorePaymentGatewayService.getInstance().doPayment(activity, paymentObject);

Note: In the doPayment(), you can send the payment object of any of the above created payment mode (CFCardPayment, CFNetbankingPayment, CFWalletPayment, CFUPIPayment, CFEMIPayment, CFPaylaterPayment)


Sample Code

package com.cashfree.sdk_sample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.cashfree.pg.api.CFPaymentGatewayService;
import com.cashfree.pg.core.api.CFCorePaymentGatewayService;
import com.cashfree.pg.core.api.CFSession;
import com.cashfree.pg.core.api.callback.CFCheckoutResponseCallback;
import com.cashfree.pg.core.api.card.CFCard;
import com.cashfree.pg.core.api.card.CFCardPayment;
import com.cashfree.pg.core.api.emicard.CFEMICard;
import com.cashfree.pg.core.api.emicard.CFEMICardPayment;
import com.cashfree.pg.core.api.exception.CFException;
import com.cashfree.pg.core.api.netbanking.CFNetBanking;
import com.cashfree.pg.core.api.netbanking.CFNetBankingPayment;
import com.cashfree.pg.core.api.upi.CFUPI;
import com.cashfree.pg.core.api.upi.CFUPIPayment;
import com.cashfree.pg.core.api.utils.CFErrorResponse;
import com.cashfree.pg.core.api.wallet.CFWallet;
import com.cashfree.pg.core.api.wallet.CFWalletPayment;

public class ElementCheckoutActivity extends AppCompatActivity  implements CFCheckoutResponseCallback {
    String orderID = "ORDER_ID";
    String paymentSessionID = "PAYMENT_SESSION_ID";
    CFSession.Environment cfEnvironment = CFSession.Environment.PRODUCTION;

    //Card Payment Inputs
    public String cardNumber = "4444111100002222";
    public String cardMM = "08";
    public String cardYY = "25";
    public String cardHolderName = "Card Holder Name";
    public String cardCVV = "111";

    // Card EMI Inputs
    public String bankName = "Axis Bank";
    public int emiTenure = 3;

    //UPI Collect mode
    public CFUPI.Mode collectMode = CFUPI.Mode.COLLECT;
    public String upiVpa = "[email protected]";

    // UPI Intent mode
    public CFUPI.Mode intentMode = CFUPI.Mode.INTENT;
    public String upiAppPackage = "com.google.android.apps.nbu.paisa.user";

    //Wallet mode
    public String channel = "phonepe";
    public String phone = "9871043819";

    // Net Banking mode
    public int bankCode = 3003;

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

    @Override
    public void onPaymentVerify(String orderID) {
        Log.e("onPaymentVerify", "verifyPayment triggered");
    }

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

    public void doCardPayment(View view) {
        try {
            CFSession cfSession = new CFSession.CFSessionBuilder()
                    .setEnvironment(cfEnvironment)
                    .setPaymentSessionID(paymentSessionID)
                    .setOrderId(orderID)
                    .build();
            CFCard cfCard = new CFCard.CFCardBuilder()
                    .setCardHolderName(cardHolderName)
                    .setCardNumber(cardNumber)
                    .setCardExpiryMonth(cardMM)
                    .setCardExpiryYear(cardYY)
                    .setCVV(cardCVV)
                    .build();
            CFCardPayment cfCardPayment = new CFCardPayment.CFCardPaymentBuilder()
                    .setSession(cfSession)
                    .setCard(cfCard)
                    .build();
            CFCorePaymentGatewayService.getInstance().doPayment(ElementCheckoutActivity.this, cfCardPayment);
        } catch (CFException exception) {
            exception.printStackTrace();
        }
    }

    public boolean hasValidCardInputs() {
        if (cardNumber.length() != 16) {
            Log.e("CARD INPUT VALIDATION", "Enter a Valid Card Number");
            return false;
        }
        if (cardHolderName.length() < 3) {
            Log.e("CARD INPUT VALIDATION", "Enter a Valid Card Holder Name");
            return false;
        }
        if (cardMM.length() != 2) {
            Log.e("CARD INPUT VALIDATION", "Enter a Valid Card Expiry Month in MM format");
            return false;
        }
        if (cardYY.length() != 2) {
            Log.e("CARD INPUT VALIDATION", "Enter a Valid Card Expiry Year in YY format");
            return false;
        }
        if (cardCVV.length() < 3 || cardCVV.length() > 4) {
            Log.e("CARD INPUT VALIDATION", "Enter a Valid Card CVV");
            return false;
        }
        return true;
    }



    public void doCardEMIPayment(View view) {
        if (hasValidCardInputs())
            try {
                CFSession cfSession = new CFSession.CFSessionBuilder()
                        .setEnvironment(cfEnvironment)
                        .setPaymentSessionID(paymentSessionID)
                        .setOrderId(orderID)
                        .build();
                CFEMICard cfCard = new CFEMICard.CFEMICardBuilder()
                        .setCardHolderName(cardHolderName)
                        .setCardNumber(cardNumber)
                        .setCardExpiryMonth(cardMM)
                        .setCardExpiryYear(cardYY)
                        .setCVV(cardCVV)
                        .setBankName(bankName)
                        .setEMITenure(emiTenure)
                        .build();
                CFEMICardPayment cfCardPayment = new CFEMICardPayment.CFEMICardPaymentBuilder()
                        .setSession(cfSession)
                        .setCard(cfCard)
                        .build();
                CFCorePaymentGatewayService.getInstance().doPayment(ElementCheckoutActivity.this, cfCardPayment);
            } catch (CFException exception) {
                exception.printStackTrace();
            }
    }



    public void doNetBankingPayment(View view) {
        if (hasValidNetBankingInputs())
            try {
                CFSession cfSession = new CFSession.CFSessionBuilder()
                        .setEnvironment(cfEnvironment)
                        .setPaymentSessionID(paymentSessionID)
                        .setOrderId(orderID)
                        .build();
                CFNetBanking cfNetBanking = new CFNetBanking.CFNetBankingBuilder()
                        .setBankCode(bankCode)
                        .build();
                CFNetBankingPayment cfNetBankingPayment = new CFNetBankingPayment.CFNetBankingPaymentBuilder()
                        .setSession(cfSession)
                        .setCfNetBanking(cfNetBanking)
                        .build();
                CFCorePaymentGatewayService.getInstance().doPayment(ElementCheckoutActivity.this, cfNetBankingPayment);
            } catch (CFException exception) {
                exception.printStackTrace();
            }
    }

    public boolean hasValidNetBankingInputs() throws IllegalArgumentException {
        if (String.valueOf(bankCode).length() != 4) {
            Log.e("NET_BANKING VALIDATION", "Enter a Valid 4 digit Bank Code");
            return false;
        }
        return true;
    }

    public void doWalletPayment(View view) {
        if (hasValidWalletPaymentInputs())
            try {
                CFSession cfSession = new CFSession.CFSessionBuilder()
                        .setEnvironment(cfEnvironment)
                        .setPaymentSessionID(paymentSessionID)
                        .setOrderId(orderID)
                        .build();
                CFWallet cfWallet = new CFWallet.CFWalletBuilder()
                        .setProvider(channel)
                        .setPhone(phone)
                        .build();
                CFWalletPayment cfWalletPayment = new CFWalletPayment.CFWalletPaymentBuilder()
                        .setSession(cfSession)
                        .setCfWallet(cfWallet)
                        .build();
                CFCorePaymentGatewayService.getInstance().doPayment(ElementCheckoutActivity.this, cfWalletPayment);
            } catch (CFException exception) {
                exception.printStackTrace();
            }
    }

    public boolean hasValidWalletPaymentInputs() throws IllegalArgumentException {
        if (channel.length() < 4) {
            Log.e("WALLET INPUT VALIDATION", "Enter a Valid channel");
            return false;
        }

        if (phone.length() < 10) {
            Log.e("WALLET INPUT VALIDATION", "Enter a Valid phone number");
            return false;
        }
        return true;
    }



    public void doUPICollectPayment(View view) {
        initiatePayment(collectMode, paymentSessionID);
    }

    public void doUPIIntentPayment(View view) {

        initiatePayment(intentMode, upiAppPackage);
    }

    private void initiatePayment(CFUPI.Mode mode, String id) {
        try {
            CFSession cfSession = new CFSession.CFSessionBuilder()
                    .setEnvironment(cfEnvironment)
                    .setPaymentSessionID(paymentSessionID)
                    .setOrderId(orderID)
                    .build();
            CFUPI cfupi = new CFUPI.CFUPIBuilder()
                    .setMode(mode)
                    .setUPIID(id)
                    .build();
            CFUPIPayment cfupiPayment = new CFUPIPayment.CFUPIPaymentBuilder()
                    .setSession(cfSession)
                    .setCfUPI(cfupi)
                    .build();
            CFCorePaymentGatewayService.getInstance().doPayment(ElementCheckoutActivity.this, cfupiPayment);
        } catch (CFException exception) {
            exception.printStackTrace();
        }
    }

}