API ReferenceIntegrationsKnowledge Base

Android SDK Integration - Razorpay Standard Checkout

Razorpay Android Standard SDK lets you easily integrate the Razorpay Payment Gateway with your Android application.

Important Notes:

  • Due to the changes in the Google Play Developer policy, we have removed auto-read SMS feature from Razorpay Android Standard SDK versions 1.5.1 and higher. However, if your Android app already has permission to read SMS, then Razorpay will auto-read it.
    If you are using older versions of Razorpay Android Standard SDK, you must upgrade to the latest version available on the Maven Repository.

  • According to PCI regulations, payment processing is not allowed on TLS v1. Hence, if the device does not have TLS v1.1 or TLS v1.2, the SDK will throw an error in the onPaymentError method. You can learn more about TLS versions here.

Video Tutorial#

Watch this video to learn how to integrate Razorpay Payment Gateway on your Android app.

Prerequisites#

  • Create a Razorpay account.
  • Generate API Keys from the Razorpay Dashboard. You can use the Test Keys for a sandbox experience. No money will be deducted from your account when making test payments. Please use the Live Keys when going live with the application.

Integration Steps#

Steps to integrate your Android application with Razorpay Android Standard SDK are given below:

  1. Install Razorpay Android Standard SDK.
  2. Initialize Razorpay Android Standard SDK.
  3. Create an Order in your Server.
  4. Initiate Payment and Display Checkout Form.
  5. Handle Success and Error Events.
  6. Store Fields in Server.
  7. Verify Payment Signature.

Post-Integration Steps:
Once you have successfully completed the integration, you can setup webhooks, make test payments, replace test key with live key and integrate with other APIs. Refer to the post-integration section for more details.

Step 1: Install Razorpay Android Standard SDK#

We distribute our SDK from the Maven Central Repository. Download the latest versions of the SDK from the Maven Repository and place the checkout-1.5.16.aar file inside the libs folder.

To add the SDK to your app, add the following dependency in your app's build.gradle file:

Copyrepositories { mavenCentral() } dependencies { implementation 'com.razorpay:checkout:1.5.16' }

Step 2: Initialize Razorpay Android Standard SDK#

Add your Razorpay <API_KEY_ID> dynamically using Checkout's setKeyId() method. You can generate the API Keys from the Razorpay Dashboard.

Copypublic class SomeEarlierMerchantActivity extends Activity { // ... @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkout.setKeyID("<YOUR_KEY_ID>"); // ... } }

Note:
It is recommended to send the API Key ID from your server-side as app related metadata fetch.

Proguard rules#

If you are using Proguard for your builds, modify the Proguard rule file:

Copy-keepclassmembers class * { @android.webkit.JavascriptInterface <methods>; } -keepattributes JavascriptInterface -keepattributes *Annotation* -dontwarn com.razorpay.** -keep class com.razorpay.** {*;} -optimizations !method/inlining/* -keepclasseswithmembers class * { public void onPayment*(...); }

Step 3: Create an Order in your Server#

Create an order using Orders API in server. This generates a order_id when the customer places an order on your app. This order_id must be passed by you during checkout.

Note:
Do not create the order on your client. Order must be created on server only.

Use the below endpoint to create an Order.

/orders
Copycurl -X POST https://api.razorpay.com/v1/orders -H 'content-type:application/json' -d '{ "amount": 50000, "currency": "INR", "receipt": "rcptid_11" }'
Copytry { JSONObject orderRequest = new JSONObject(); orderRequest.put("amount", 50000); // amount in the smallest currency unit orderRequest.put("currency", "INR"); orderRequest.put("receipt", "order_rcptid_11"); Order order = razorpay.Orders.create(orderRequest); } catch (RazorpayException e) { // Handle Exception System.out.println(e.getMessage()); }
Copyorder_amount = 50000 order_currency = 'INR' order_receipt = 'order_rcptid_11' notes = {'Shipping address': 'Bommanahalli, Bangalore'} # OPTIONAL client.order.create(amount=order_amount, currency=order_currency, receipt=order_receipt, notes=notes)
Copy$order = $client->order->create([ 'receipt' => 'order_rcptid_11', 'amount' => 50000, // amount in the smallest currency unit 'currency' => 'INR',// <a href="/docs/payment-gateway/payments/international-payments/#supported-currencies" target="_blank">See the list of supported currencies</a>.) ]);
CopyDictionary<string, object> options = new Dictionary<string,object>(); options.Add("amount", 50000); // amount in the smallest currency unit options.add("receipt", "order_rcptid_11"); options.add("currency", "INR"); Order order = client.Order.Create(options);
Copyoptions = amount: 50000, currency: 'INR', receipt: '<order_rcptid_11>', order = Razorpay::Order.create
Copyvar options = { amount: 50000, // amount in the smallest currency unit currency: "INR", receipt: "order_rcptid_11" }; instance.orders.create(options, function(err, order) { console.log(order); });
Copy{ "id": "order_DBJOWzybf0sJbb", "entity": "order", "amount": 50000, "amount_paid": 0, "amount_due": 50000, "currency": "INR", "receipt": "rcptid_11", "status": "created", "attempts": 0, "notes": [], "created_at": 1566986570 }

Successful creation of the Order returns an id (referred to as order_id) that should be stored against the Order defined in your system.

Read more: Learn more about Orders API.

Request Parameters#

amount mandatory
integer The transaction amount, expressed in the currency subunit, such as paise (in case of INR). For example, for an actual amount of ₹299.35, the value of this field should be 29935.
currency mandatory
string The currency in which the transaction should be made. See the list of supported currencies. Default is INR.
receipt optional
string Your receipt id for this order should be passed here. Maximum length 40 characters.
notes optional
object Key-value pair that can be used to store additional information about the entity. Maximum 15 key-value pairs, 256 characters (maximum) each. For example, "note_key": "Beam me up Scotty”.

Step 4: Initiate Payment and Display Checkout Form#

Preload Checkout#

To quickly load the Checkout form, the preload method of Checkout must be called much earlier than the other methods in the payment flow. The loading time of the preload resources can vary, depending on your network's bandwidth.

Copypublic class SomeEarlierMerchantActivity extends Activity { // ... @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** * Preload payment resources */ Checkout.preload(getApplicationContext()); // ... } // ... }
Copyclass PaymentActivity: Activity(), PaymentResultListener { val TAG:String = PaymentActivity::class.toString() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_payment) /* * To ensure faster loading of the Checkout form, * call this method as early as possible in your checkout flow * */ Checkout.preload(applicationContext) var button: Button = findViewById(R.id.btn_pay) button.setOnClickListener { startPayment() } }

Initiate a Payment#

Create an instance of Checkout and pass the payment details and options as a JSONObject. Ensure that you add the order_id generated in Step 1. Complete list of checkout parameters is available here.

Copypublic void startPayment() { checkout.setKeyID("<YOUR_KEY_ID>"); /** * Instantiate Checkout */ Checkout checkout = new Checkout(); /** * Set your logo here */ checkout.setImage(R.drawable.logo); /** * Reference to current activity */ final Activity activity = this; /** * Pass your payment options to the Razorpay Checkout as a JSONObject */ try { JSONObject options = new JSONObject(); options.put("name", "Merchant Name"); options.put("description", "Reference No. #123456"); options.put("image", "https://s3.amazonaws.com/rzp-mobile/images/rzp.png"); options.put("order_id", "order_DBJOWzybf0sJbb");//from response of step 3. options.put("theme.color", "#3399cc"); options.put("currency", "INR"); options.put("amount", "50000");//pass amount in currency subunits options.put("prefill.email", "gaurav.kumar@example.com"); options.put("prefill.contact","9988776655"); checkout.open(activity, options); } catch(Exception e) { Log.e(TAG, "Error in starting Razorpay Checkout", e); } }
Copyprivate fun startPayment() { /* * You need to pass current activity in order to let Razorpay create CheckoutActivity * */ val activity:Activity = this val co = Checkout() try { val options = JSONObject() options.put("name","Razorpay Corp") options.put("description","Demoing Charges") //You can omit the image option to fetch the image from dashboard options.put("image","https://s3.amazonaws.com/rzp-mobile/images/rzp.png") options.put("theme.color", "#3399cc"); options.put("currency","INR"); options.put("order_id", "order_DBJOWzybf0sJbb"); options.put("amount","50000")//pass amount in currency subunits val prefill = JSONObject() prefill.put("email","gaurav.kumar@example.com") prefill.put("contact","9876543210") options.put("prefill",prefill) co.open(activity,options) }catch (e: Exception){ Toast.makeText(activity,"Error in payment: "+ e.message,Toast.LENGTH_LONG).show() e.printStackTrace() } }

Note:
When you paste the checkout options shown above, the following error message appears:
'TAG has private access in androidx.fragment.app.FragmentActivity'


You can resolve this by adding the following code as shown:

Copypublic class MainActivity extends AppCompatActivity implements PaymentResultListener { private static final String TAG = MainActivity.class.getSimpleName();

Checkout.open() launches the Checkout form where the customer completes the payment and returns the payment result via appropriate callbacks on the PaymentResultListener.

Payment Options in JSONObject: All available options in the Standard Web Checkout are also available in Android.

The Checkout fields used in both the Checkout methods are explained in this table:

Field Name (Manual)

Field Name (Automatic)

Required

Description

key

data-key

Yes

Merchant Key-ID

amount

data-amount

Yes

Payment amount Accepted datatype is integer. For example, if the amount is ₹100,data-amount="10000".

currency

data-currency

Yes

The currency in which the payment should be made by the customer. See the list of supported currencies.

If you are using Razorpay Orders, the currency in which the payment is made must match the Order currency.

name

data-name

Yes

The merchant/company name shown in the Checkout form.

description

data-description

No

Description of the purchased item shown in the Checkout form. Must start with an alphanumeric character.

image

data-image

No

Link to an image (usually merchant's logo) shown in the Checkout form. Can also be a base64 string, if loading image from network is not desirable.

order_id

data-order_id

Yes

Order ID generated via Orders API

prefill.name

data-prefill.name

No

Cardholder name to be pre-filled when the Checkout opens.

prefill.email

data-prefill.email

No

Customer's email to be pre-filled when the Checkout opens.

prefill.contact

data-prefill.contact

No

Customer's phone number to be pre-filled when the Checkout opens.

The expected format of the phone number is + {country code}{phone number}. If the country code is not specified, 91 will be used as the default value. This is particularly important while prefilling contact of customers with phone numbers issued outside India.

Examples:
● +14155552671 (a valid non-Indian number)
● +919977665544 (a valid Indian number).
If 9977665544 is entered, +91 is added to it as +919977665544.

prefill.method

data-prefill.method

No

Pre-selection of the payment method for the customer. It can be card/netbanking/wallet/emi/upi. However, it will only work if contact and email are also pre-filled.

notes.fieldname

data-notes.fieldname

No

Any additional fields you want to associate with the payment. For example, "shipping address". Up to 15 note fields can be specified in this way.

theme.hide_topbar

data-theme.hide_topbar

No

Used to display or hide the top bar on the checkout form. This bar shows the selected payment method, phone number and gives the customer the option to navigate back to the start of the checkout form. Possible values are true - Hides the top bar, and false - Displays the top bar.

theme.color

data-theme.color

No

Brand color to alter the appearance of Checkout form.

modal.backdropclose

data-modal.backdropclose

No

This field accepts a boolean value indicating whether clicking the translucent blank space outside Checkout form should close the form. Defaults to false.

modal.escape

data-modal.escape

No

This field accepts a boolean value indicating whether pressing escape key should close the Checkout form. Defaults to true.

modal.handleback

data-modal.handleback

No

When set as 'true', Checkout behaves similarly to the browser. That is, when the browser's back button is pressed, the Checkout also simulates a back press. This happens as long as the Checkout modal is open. By default, this is set to true.

Note:
If you are calling the payment start method from inside a fragment, ensure that the fragment's parent activity implements the PaymentResultListener interface.

Step 5: Handle Success and Error Events#

You have the option to implement PaymentResultListener or PaymentResultWithDataListener to receive callbacks for the payment result.

PaymentResultListener provides only payment_id as the payment result. PaymentResultWithDataListener provides additional payment data, such as email and contact of the customer, along with the order_id, payment_id, signature and more.

Copypublic class MerchantActivity extends Activity implements PaymentResultListener { // ... @Override public void onPaymentSuccess(String razorpayPaymentID) { /** * Add your logic here for a successful payment response */ } @Override public void onPaymentError(int code, String response) { /** * Add your logic here for a failed payment response */ } }
Copyclass PaymentActivity: Activity(), PaymentResultListener { // ... override fun onPaymentError(errorCode: Int, response: String?) { /** * Add your logic here for a failed payment response */ } override fun onPaymentSuccess(razorpayPaymentId: String?) { /** * Add your logic here for a successful payment response */ }
Copyrazorpay.submit(data, new PaymentResultWithDataListener() { @Override public void onPaymentSuccess(String razorpayPaymentId, PaymentData paymentData) { // Razorpay payment ID and PaymentData passed here after a successful payment } @Override public void onPaymentError(int code, String description) { // Error code and description is passed here } }); } catch (Exception e) { Log.e(TAG, "Error in submitting payment details", e); }
Copyrazorpay?.submit(payload,object:PaymentResultWithDataListener{ override fun onPaymentError(errorCode: Int, errorDescription: String?, paymentData: PaymentData?) { webView?.visibility = View.GONE outerBox?.visibility = View.VISIBLE Toast.makeText(this@PaymentOptions, "Error $errorCode : $errorDescription",Toast.LENGTH_LONG).show() Log.e(TAG,"onError: $errorCode : $errorDescription : ${paymentData?.data.toString()}") } override fun onPaymentSuccess(rzpPaymentId: String?, paymentData: PaymentData?) { webView?.visibility = View.GONE outerBox?.visibility = View.VISIBLE Toast.makeText(this@PaymentOptions, "Payment Successful: $rzpPaymentId \n data: ${paymentData?.orderId}",Toast.LENGTH_LONG).show() } })

Your Activity Can Get Recreated:

  • Razorpay's payment process takes place in a new activity. Once the payment is complete, the SDK hands over control to a layer which calls these callback methods. Since there are two activities involved, your activity can get garbage collected/ destroyed in case the device is low on memory. Hence, these two methods should not depend on any variable that is not set through your life cycle hooks.
  • It is recommended that you test everything by enabling "Don't Keep Activities" in Developer Options under Settings.

Error codes#

The error codes that are returned in the onPaymentError method are:

Error_Code

Description

Checkout.NETWORK_ERROR

There was a network error. For example, loss of internet connectivity.

Checkout.INVALID_OPTIONS

An issue with options passed in checkout.open.

Checkout.PAYMENT_CANCELED

User cancelled the payment.

Checkout.TLS_ERROR

The device does not support TLS v1.1 or TLS v1.2.

Erase User Data from SDK#

The SDK stores customer-specific data such as email, contact number and user-session cookies, in case the customer wants to make another payment in the same session. You can delete such sensitive information before another customer logs into the app.

To erase customer data from the app, you can call the following method anywhere in your app.

CopyCheckout.clearUserData(Context)

Note:
Contact our Support Team if you have any queries.

Step 6: Store the Fields in Server#

A successful payment returns the following fields to the Checkout Form. Make provisions to store these fields on your server. You can confirm the authenticity of these details by verifying the signature in the next step.

Copy{ "razorpay_payment_id": "pay_29QQoUBi66xm2f", "razorpay_order_id": "order_9A33XWu170gUtm", "razorpay_signature": "9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d" }
razorpay_payment_id
string Unique identifier for the payment returned by Checkout only for successful payments.
razorpay_order_id
string Unique identifier for the order returned by Checkout.
razorpay_signature
string Signature returned by the checkout. This is used to verify the payment.

Step 7: Verify Payment Signature#

This is a mandatory step that allows you to confirm the authenticity of the details returned to the Checkout form for successful payments.

To verify the razorpay_signature returned to you by the Checkout form:

  1. Create a signature in your server using the following attributes:

    • order_id - Retrieve the order_id from your server. Do not use the razorpay_order_id returned by Checkout.
    • razorpay_payment_id - Returned by Checkout.
    • key_secret - Available in your server.
      The key_secret that was generated from the Dashboard.
  2. Use the SHA256 algorithm, the razorpay_payment_id and the order_id to construct a HMAC hex digest as shown below:

    Copygenerated_signature = hmac_sha256(order_id + "|" + razorpay_payment_id, secret); if (generated_signature == razorpay_signature) { payment is successful }
  3. If the signature you generate on your server matches the razorpay_signature returned to you by the Checkout form, the payment received is from an authentic source.

Generate Signature on your Server#

Copy/** * This class defines common routines for generating * authentication signatures for Razorpay Webhook requests. */ public class Signature { private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; /** * Computes RFC 2104-compliant HMAC signature. * * @param data * The data to be signed. * @param key * The signing key. * @return * The Base64-encoded RFC 2104-compliant HMAC signature. * @throws * java.security.SignatureException when signature generation fails */ public static String calculateRFC2104HMAC(String data, String secret) throws java.security.SignatureException { String result; try { // get an hmac_sha256 key from the raw secret bytes SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA256_ALGORITHM); // get an hmac_sha256 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac result = DatatypeConverter.printHexBinary(rawHmac).toLowerCase(); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; } }
Copyuse Razorpay\Api\Api; $api = new Api($key_id, $key_secret); $attributes = array('razorpay_signature' => '23233', 'razorpay_payment_id' => '332' , 'order_id' => '12122'); $order = $api->utility->verifyPaymentSignature($attributes)
Copyrequire 'razorpay' Razorpay.setup('key_id', 'key_secret') payment_response = { 'order_id': '12122', 'razorpay_payment_id': '332', 'razorpay_signature': '23233' } Razorpay::Utility.verify_payment_signature(payment_response)
Copyimport razorpay client = razorpay.Client(auth = ('<key_id>', '<key_secret>')) params_dict = { 'order_id': '12122', 'razorpay_payment_id': '332', 'razorpay_signature': '23233' } client.utility.verify_payment_signature(params_dict)

Post Signature Verification#

After verifying the signature, fetch the order in your system that corresponds to the razorpay_order_id in your database. Mark it as successful and process the order.

Test the Integration#

Now that the integration is complete, you must ensure that your integration works as expected. You can make a test transaction using the test cards, verify the payment status from Dashboard, APIs or subscribe to related Webhook events to take appropriate actions at your end. After testing the integration in test mode, you can start accepting payments from your customers in real-time.

Test Payments#

You can make test payments using any of the payment methods configured on the Checkout. No money is deducted from the customer's account as this is a simulated transaction. In the Checkout code, ensure that you have entered the API keys generated in the test mode.

Test Cards#

You can use any of the test cards to make transactions in the test mode. Use any valid expiration date in the future and any random CVV to create a successful payment.

Card Network

Domestic / International

Card Number

Mastercard

Domestic

5104 0155 5555 5558
5104 0600 0000 0008

Visa

Domestic

4111 1111 1111 1111

Mastercard

International

5555 5555 5555 4444
5105 1051 0510 5100

Visa

International

4012 8888 8888 1881
4000 1841 8621 8826

Verify the Payment Status#

You can track the status of the payment from the Dashboard or subscribe to the Webhook event or poll our APIs.

From the Dashboard#

  1. Log into your Dashboard and navigate to TransactionsPayments.
  2. Look if a payment_ID has been generated. If no payment_ID has been generated, it means that the transaction has failed.

Subscribe to Webhook events#

You can subscribe to a Webhook event that is generated when a certain event happens in our server. When one of those events is triggered, Razorpay sends the Webhook payload to the configured URL.

Learn how to set up Webhooks.

When the customer makes a successful payment on the Checkout, payment.authorized event is created in Razorpay.

Poll APIs#

You can retrieve the status of the payments by polling our Payment APIs.

Accept Live Payments#

After testing the flow of funds end-to-end in test mode, you are now ready to take your integration live. Once you are confident that the integration is working fine, you can switch to the live mode and start accepting payments from customers. But first, you need to swap the test API keys with the live keys.

To generate API key in live mode:

  1. Log into Dashboard and switch to Live mode on the menu.
  2. Navigate to SettingsAPI KeysGenerate Key to generate API key for live mode.
  3. Download the keys and save it securely.
  4. Replace the test API key with the Live Key in the Checkout code and start accepting real-time payments.

Timeouts#

The transaction timeout is applicable only when your customer attempts the payment.

The timeout is 3 to 15 minutes for an attempted payment. If there is a payment failure due to timeout, the customer is redirected to the Checkout page.