How To Integrate Razorpay In Android

Introduction

 
A payment gateway is an indispensible part of any Android application. There are many payment gateways available in the market, but today we will learn about a very popular payment gateway known as Razorpay. Razorpay Android Standard SDK lets you easily integrate the Razorpay Payment Gateway with your Android application.
 
Prerequisites
  • Create Razorpay account
  • Generate test and live keys from dashboard. (Test keys are easy to test in that there will be no deduction of money.)
After creation of Razorpay account go to dashboard and generate a test key for testing purposes like shown in the image below.

How To Integrate Razorpay In Android
 
The key will look like : rzp_test_LdI1ob5rGXZDF6

Integration Steps

 
Step 1 - Add Razorpay sdk to your build.gradle file
  1. repositories {  
  2.     mavenCentral()  
  3. }  
  4.   
  5. dependencies {  
  6.     implementation 'com.razorpay:checkout:1.5.16'  
  7. }  
Step 2 - Initialize the key id
  1. @Override  
  2.  public void onCreate(Bundle savedInstanceState) {  
  3.    super.onCreate(savedInstanceState);  
  4.   
  5.    checkout.setKeyID("rzp_test_LdI1ob5rGXZDF6");  
  6.   
  7.    // ...  
  8.  }  
We will see the full code later on.
 
Step 3 - Create order on server (Optional)

You can use your backened custom order id. Create an order using Orders API in server. This generates an order_id when the customer places an order on your app. This order_id must be passed by you during checkout. 
  1. try {  
  2.   JSONObject orderRequest = new JSONObject();  
  3.   orderRequest.put("amount"12000); // amount in the smallest currency unit  
  4.   orderRequest.put("currency""INR");  
  5.   orderRequest.put("receipt""order_rcptid_11");  
  6.   
  7.   Order order = razorpay.Orders.create(orderRequest);  
  8. catch (RazorpayException e) {  
  9.   // Handle Exception  
  10.   System.out.println(e.getMessage());  
  11. }  
In Response you will get order id like below 
  1. {  
  2.     "id""order_DBJOWzybf0sJbb",  
  3.     "entity""order",  
  4.     "amount": 50000,  
  5.     "amount_paid": 0,  
  6.     "amount_due": 50000,  
  7.     "currency""INR",  
  8.     "receipt""rcptid_11",  
  9.     "status""created",  
  10.     "attempts": 0,  
  11.     "notes": [],  
  12.     "created_at": 1566986570  
  13. }  
The above steps are optional we will see the payment checkout without order id.

Step 4 - Inititate payment 

Firstly we have created some xml to show what we are checking out -- let's see our xml file activity_main.xml
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"    
  4.     xmlns:tools="http://schemas.android.com/tools"    
  5.     android:layout_width="match_parent"    
  6.     android:layout_height="match_parent"    
  7.     tools:context=".MainActivity">    
  8.     
  9.    <ImageView    
  10.        android:id="@+id/imageview"    
  11.        android:layout_width="300dp"    
  12.        android:layout_height="300dp"    
  13.        android:src="@drawable/ic_tea"    
  14.        android:layout_centerInParent="true">    
  15.     
  16.    </ImageView>    
  17.     
  18.     <TextView    
  19.         android:id="@+id/textview"    
  20.         android:layout_width="wrap_content"    
  21.         android:layout_height="wrap_content"    
  22.         android:text="Buy for 120rs"    
  23.         android:textSize="18sp"    
  24.         android:textStyle="bold"    
  25.         android:background="#90EE90"    
  26.         android:padding="12dp"    
  27.         android:layout_below="@id/imageview"    
  28.         android:layout_centerHorizontal="true"/>    
  29.     
  30. </RelativeLayout>    
Now for the corresponding java part, see MainActivity.java
  1. package com.example.razorpaytest;  
  2.   
  3. import androidx.appcompat.app.AppCompatActivity;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.widget.TextView;  
  9. import android.widget.Toast;  
  10.   
  11. import com.razorpay.Checkout;  
  12. import com.razorpay.PaymentData;  
  13. import com.razorpay.PaymentResultWithDataListener;  
  14.   
  15. import org.json.JSONObject;  
  16.   
  17. public class MainActivity extends AppCompatActivity implements PaymentResultWithDataListener {  
  18.   
  19.     TextView buyButton;  
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.         buyButton = findViewById(R.id.textview);  
  26.   
  27.         Checkout.preload(getApplicationContext()); // For faster rendering of payment screen  
  28.   
  29.   
  30.         buyButton.setOnClickListener(new View.OnClickListener() {  
  31.             @Override  
  32.             public void onClick(View v) {  
  33.   
  34.                 startPayment();  
  35.   
  36.             }  
  37.         });  
  38.     }  
  39.   
  40.   
  41.     public void startPayment() {  
  42.   
  43.         //     You need to pass current activity in order to let Razorpay create CheckoutActivity  
  44.   
  45.         final Activity activity = this;  
  46.   
  47.         final Checkout co = new Checkout();  
  48.         co.setKeyID("rzp_test_LdI1ob5rGXZDF6");  
  49.         try {  
  50.   
  51.   
  52.             // amount to be in paisa only  
  53.   
  54.   
  55.             int finalAmount = 120*100// converting 12p rupees into paisa  
  56.   
  57.             JSONObject options = new JSONObject();  
  58.             options.put("name""RazorPayTestApp");  
  59.             options.put("description""Test Payment");  
  60.             //You can omit the image option to fetch the image from dashboard  
  61.             //   options.put("image", "https://s3.amazonaws.com/rzp-mobile/images/rzp.png");  
  62.             options.put("currency""INR");  
  63.             options.put("amount", String.valueOf(finalAmount));  
  64.   
  65.             //      options.put("order_id", order_DBJOWzybf0sJbb);//from response of step 3.  
  66.   
  67.             JSONObject preFill = new JSONObject();  
  68.             preFill.put("email""[email protected]");  
  69.             preFill.put("contact""858681XXXX");  
  70.   
  71.             JSONObject notes = new JSONObject();  
  72.             notes.put("Product_details","Here are the notes");  
  73.   
  74.             options.put("prefill", preFill);  
  75.             options.put("notes",notes);  
  76.   
  77.             co.open(activity, options);  
  78.         } catch (Exception e) {  
  79.             Toast.makeText(activity, "Error in payment: " + e.getMessage(), Toast.LENGTH_SHORT)  
  80.                     .show();  
  81.             e.printStackTrace();  
  82.   
  83.         }  
  84.     }  
  85.   
  86.     @Override  
  87.     public void onPaymentSuccess(String id, PaymentData paymentData) {  
  88.   
  89.         Toast.makeText(this"Payment Success with id : "+id, Toast.LENGTH_SHORT).show();  
  90.   
  91.     }  
  92.   
  93.     @Override  
  94.     public void onPaymentError(int i, String response, PaymentData paymentData) {  
  95.         Toast.makeText(this, response, Toast.LENGTH_SHORT).show();  
  96.     }  
  97. }  
Here we are starting chekout activity on a button click see startPayment() method on a button click.
 
Step 5 - Handle success and error events
  1. public class MainActivity extends AppCompatActivity implements PaymentResultWithDataListener {

  2. @Override  
  3.  public void onPaymentSuccess(String razorpayPaymentID) {  
  4.     /** 
  5.     * Add your logic here for a successful payment response 
  6.     */  
  7.  }  
  8.   
  9.  @Override  
  10.  public void onPaymentError(int code, String response) {  
  11.     /** 
  12.     * Add your logic here for a failed payment response 
  13.     */  
  14.  }  
  15. }
You can see the full code above to get better idea of what we are doing in success and error listeners.
 
Running application

How To Integrate Razorpay In Android

Now tap on Buy button for 120 rupees.

How To Integrate Razorpay In Android

Now tap on Pay button and you will get confirmation.

How To Integrate Razorpay In Android

Now tap on success -- this screen will not be shown on live payments.

How To Integrate Razorpay In Android

Payment confirmation 

How To Integrate Razorpay In Android
 

Summary


In this article we have learnt about the integration of Razorpay. This is the easiest way one can integrate the payment sdk. Once you sign up and add your details over it you can capture money from right there. 


Similar Articles