In this tutorial, we will learn the fundamentals of integrating Razorpay Checkout into an Android app using Java and XML layouts.
We will cover project configuration, checkout UI, payment amounts, payment callbacks, server-side order creation, and the security checks required before treating a transaction as successful.
Important: Opening checkout and receiving a client-side success callback does not, by itself, prove that a payment has been verified. A production application must create orders on a trusted backend and verify payment results on the server.
What We Will Build
Our example will include:
A simple payment screen.
A button to initiate checkout.
Razorpay Checkout SDK integration.
Payment success and failure callbacks.
A backend-created Razorpay order.
Guidance for secure payment verification.
Requirements
Before starting, make sure you have:
Android Studio.
A Java-based Android project.
A Razorpay account.
Test-mode API credentials.
A backend capable of creating Razorpay orders.
An internet connection.
Razorpay's Android Checkout SDK has its own minimum SDK and dependency requirements. Check the current official Android integration documentation before selecting your Android configuration and SDK version.
Step 1: Create a Razorpay Account
Visit Razorpay and create or sign in to your account.
Use Test Mode while developing and testing your integration.
You will need:
A Razorpay Key ID.
A Razorpay Key Secret for server-side API operations.
A backend endpoint to create orders.
Never put your Key Secret in Android code, an APK, or a public GitHub repository. The Android app should use only the appropriate public Key ID and data returned by your backend.
Step 2: Create an Android Project
Open Android Studio and create a new project with Java and XML layouts.
For this tutorial, we will use a simple Activity-based interface.
Example package name:
com.example.razorpayexampleUse your own package name consistently if it differs.
Step 3: Add the Razorpay SDK Dependency
In the app-level build.gradle file, add the Razorpay Checkout SDK dependency:
dependencies {
implementation 'com.razorpay:checkout:1.6.41'
}If your project uses Kotlin DSL, use:
dependencies {
implementation("com.razorpay:checkout:1.6.41")
}The version shown is a reference version, not a guarantee of compatibility with every current Android Gradle Plugin or build configuration. Check the official Razorpay Android sample project and the SDK release information before using it in a new project.
Sync Gradle after adding the dependency.
Step 4: Configure AndroidManifest.xml
Add the internet permission to your manifest:
<uses-permission
android:name="android.permission.INTERNET" />For example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission
android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity
android:name=".CheckoutActivity"
android:exported="false" />
</application>
</manifest>If your project already has a launcher Activity, retain its existing declaration and launcher intent filter. Do not replace your complete manifest with this minimal example without adapting it to your app.
The SDK's setup requirements may vary by version. Follow its current integration documentation for any additional manifest or build configuration.
Step 5: Create the Checkout Screen
Create res/layout/activity_checkout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="24dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Complete Your Payment"
android:textSize="22sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="24dp" />
<Button
android:id="@+id/buttonPay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pay Now" />
</LinearLayout>This screen intentionally does not allow the user to determine the final amount. The amount should come from a trusted server-side order, especially when purchasing a product, subscription, or service.
Step 6: Understand the Correct Payment Flow
A secure payment flow looks like this:
The customer selects a product or service in the Android app.
The app requests an order from your backend.
The backend validates the purchase and calculates the amount.
The backend creates a Razorpay order using its secret credentials.
The backend returns the Razorpay order ID and amount to the app.
The app opens Razorpay Checkout with that order ID.
The customer completes or cancels checkout.
The app sends the payment result to the backend.
The backend verifies the result and updates the order status.
The server—not the Android app—must decide whether an order is paid.
Step 7: Create the Order on Your Backend
Before opening checkout, your backend must create a Razorpay order using the server-side Orders API.
Conceptually, your backend should expose an endpoint such as:
POST /api/payments/create-orderThe authenticated app sends the product or service identifier, not a trusted final price.
The backend should then:
Authenticate the customer.
Look up the product or service price in its own database.
Calculate the total amount in integer paise.
Create a Razorpay order using the server-side API and Key Secret.
Store the local order record and the Razorpay order ID.
Return the order ID, amount, and currency to the app.
Example response:
{
"order_id": "order_example123",
"amount": 50000,
"currency": "INR"
}This is illustrative data, not a real order.
The example represents ₹500 as 50000 paise. Your backend must generate the real order ID and amount using the actual purchase details.
See the Razorpay Orders API documentation.
Step 8: Open Razorpay Checkout in Java
The following example demonstrates how to open checkout after your backend has returned a valid Razorpay order ID and amount.
For clarity, createOrderFromBackend() represents your own HTTPS API integration. It must be implemented to call your backend on a background thread and return a validated order response before checkout opens.
Create CheckoutActivity.java:
package com.example.razorpayexample;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.razorpay.Checkout;
import com.razorpay.PaymentResultListener;
import org.json.JSONObject;
public class CheckoutActivity extends AppCompatActivity
implements PaymentResultListener {
private Button buttonPay;
// Use your Razorpay Key ID, never your Key Secret.
private static final String RAZORPAY_KEY_ID =
"rzp_test_REPLACE_WITH_YOUR_KEY_ID";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
buttonPay = findViewById(R.id.buttonPay);
buttonPay.setOnClickListener(view -> {
buttonPay.setEnabled(false);
// Implement this call using your HTTPS backend.
// Do not open checkout until a real order has
// been created and returned by your server.
createOrderFromBackend();
});
}
private void createOrderFromBackend() {
/*
* Implement your HTTPS API request here.
*
* Expected backend response:
* {
* "order_id": "order_...",
* "amount": 50000,
* "currency": "INR"
* }
*
* Execute the network request on a background thread.
* After receiving and validating the response, invoke
* openCheckout(orderId, amount, currency) on the
* Android main thread.
*
* This placeholder deliberately does not fabricate an
* order ID or claim that payment is ready.
*/
buttonPay.setEnabled(true);
Toast.makeText(
this,
"Connect your backend order API first",
Toast.LENGTH_LONG
).show();
}
private void openCheckout(
String orderId,
int amountPaise,
String currency
) {
if (orderId == null || orderId.trim().isEmpty()) {
buttonPay.setEnabled(true);
Toast.makeText(
this,
"A valid order ID is required",
Toast.LENGTH_LONG
).show();
return;
}
if (amountPaise <= 0) {
buttonPay.setEnabled(true);
Toast.makeText(
this,
"Invalid order amount",
Toast.LENGTH_LONG
).show();
return;
}
try {
Checkout checkout = new Checkout();
checkout.setKeyID(RAZORPAY_KEY_ID);
JSONObject options = new JSONObject();
options.put("name", "CodeChain Dev");
options.put("description", "Order Payment");
options.put("order_id", orderId);
options.put("amount", amountPaise);
options.put("currency", currency);
checkout.open(this, options);
} catch (Exception exception) {
buttonPay.setEnabled(true);
Toast.makeText(
this,
"Unable to open checkout",
Toast.LENGTH_LONG
).show();
}
}
@Override
public void onPaymentSuccess(String razorpayPaymentId) {
buttonPay.setEnabled(true);
Toast.makeText(
this,
"Payment submitted. Verifying with server...",
Toast.LENGTH_LONG
).show();
/*
* Send the payment ID and your local order reference
* to your backend for verification.
*
* Do not mark the order as paid based only on this
* client callback.
*/
}
@Override
public void onPaymentError(
int code,
String response
) {
buttonPay.setEnabled(true);
Toast.makeText(
this,
"Checkout did not complete. Check order status.",
Toast.LENGTH_LONG
).show();
/*
* Handle cancellation and errors appropriately.
* Reconcile the order status with the backend when
* necessary instead of assuming every callback means
* the same thing.
*/
}
}Implementation note: This is an integration skeleton, not a complete runnable payment application. The backend request and post-payment verification must be implemented before a real transaction can be completed securely. Also, use the callback interfaces and checkout options documented for the exact SDK version in your project.
Step 9: Understand Amounts in Paise
Razorpay order amounts are represented in the smallest currency unit for INR: paise.
| Amount in INR | Amount in paise |
|---|---|
| ₹1 | 100 |
| ₹50 | 5,000 |
| ₹500 | 50,000 |
| ₹1,000 | 100,000 |
Avoid calculating payment amounts using floating-point arithmetic such as:
double amount = price * 100;Floating-point numbers can represent some decimal values imprecisely. For a payment, calculate and validate the amount on the backend using integer paise or an appropriate decimal type, then send the integer amount to the Android app.
Do not let the app submit an arbitrary amount and trust it as the final price for a real purchase.
Step 10: Verify the Payment on Your Backend
This is the most important security step.
After checkout, the Android app should report the payment result to your backend. Your backend must verify the payment using the appropriate Razorpay mechanism before changing the local order status.
Depending on the integration, this includes:
Verifying the checkout signature using the server-side secret.
Confirming the payment and order relationship.
Checking the amount and currency against the original order.
Handling payment failures, pending payments, and duplicate callbacks.
Processing Razorpay webhooks with signature verification.
Updating the order status idempotently.
The secret used for signature verification must remain on the server.
Do not rely on a Toast message, a callback, or a client-supplied status such as "success" as proof of payment.
Read the official Razorpay payment signature verification documentation and webhook documentation when implementing the backend.
Step 11: Test Your Integration
Use Razorpay Test Mode and follow the current official test instructions.
Verify that:
The backend creates a real test order.
Checkout opens with the correct order ID and amount.
Successful test payments are verified by the backend.
Failed or cancelled payments are handled correctly.
Repeated callbacks do not create duplicate fulfilments.
The app does not reveal secret credentials.
Production and test credentials are kept separate.
Never test by treating a hardcoded order ID or a simulated success message as a real payment.
Common Mistakes Developers Make
1. Using the Key Secret in Android
The Key Secret is private server-side credential material. Never package it inside the Android application.
2. Opening checkout without a server-created order
For a production integration, create an order on the backend and pass its order ID into checkout.
3. Trusting the payment callback
A client-side callback is not sufficient to fulfil a paid order. Verify payment status and authenticity on the server.
4. Calculating the final amount on the client
A modified app can change client-side values. The backend must calculate and validate the amount.
5. Ignoring duplicate payment events
Callbacks and webhook events may be retried. Use idempotent order updates so an order is not fulfilled twice.
6. Publishing test credentials or private credentials
Use the correct environment and never commit private secrets to public source control.
Razorpay vs UPI Intent
| Razorpay Checkout | Direct UPI intent |
|---|---|
| Hosted checkout integration | Opens a compatible UPI app |
| Supports payment methods enabled for the account and integration | Primarily initiates a UPI payment flow |
| Can provide order and payment APIs | Requires your own reliable payment-status reconciliation |
| Suitable for an integrated gateway workflow | May be suitable for simpler UPI-focused use cases |
The right option depends on your payment requirements, provider terms, user experience, and reconciliation needs.
Frequently Asked Questions
Does Razorpay support UPI?
Razorpay supports UPI and other payment methods according to the account, product, and checkout configuration. Check the current documentation for supported methods.
Can I test payments without charging real money?
Yes. Razorpay provides a Test Mode for development. Follow the current official test-payment instructions.
Is backend verification necessary?
Yes. A production app must verify payment results on a trusted backend before treating an order as paid.
Can I put the Razorpay Key ID in an Android app?
The Key ID is intended to identify your Razorpay account in the client integration. It is not the same as the Key Secret. Never expose the Key Secret in the Android app.
Can I accept payments using only Android code?
You can demonstrate checkout integration in a client-side sample, but a secure production payment workflow requires a trusted backend for order creation, verification, and fulfilment.
Conclusion
Razorpay Checkout provides an integration path for accepting payments in Android applications. Using the SDK, developers can open checkout, handle payment callbacks, and connect the UI to a server-side order workflow.
For a secure production application, create orders on the backend, calculate amounts in integer paise, verify payment authenticity on the server, and handle duplicate or delayed payment events safely.
No comments:
Post a Comment