1. Build Integration

Steps to integrate Razorpay Payment Gateway with Java SDK.


Follow the steps given below to integrate Razorpay Payment Gateway with your Java website. The integration process is explained using the Java sample app, which contains the following files:

File Name

Purpose

index.jsp

Contains the checkout code.

OrderCreation.java

Contains the Orders API code.

Handy Tips

  • The amount must always be in currency subunits.
  • The time is represented as Unix timestamp, which can be obtained using the Utils.ToUnixTimestamp method.

To integrate Razorpay Payment Gateway with Java SDK:

1.1 Install Razorpay Java SDK.

1.2 Create an Order in Server.

1.3 Add Checkout Options.

1.4 Store Fields in Server.

1.5 Verify Payment Signature.

1.6 Verify Payment Status.

1.1 Install Razorpay Java SDK🔗

You can install Razorpay using Maven or Gradle.

Maven🔗

  1. Download and install Maven on your system.

  2. Download the latest Source code zip file from the Releases section of GitHub.

  3. Unzip the file and add this dependency to the project object model (POM) of your project.

    Copy<dependency> <groupId>com.razorpay</groupId> <artifactId>razorpay-java</artifactId> <version>x.y.z</version> //x.y.z = the version you want to install </dependency>

Gradle🔗

  1. Download and install Gradle on your system.

  2. Download the latest Source code zip file from the Releases section of GitHub.

  3. Unzip the file and add this dependency to the build file of the project:

    Copyimplementation 'com.razorpay:razorpay-java:x.y.z" //x.y.z = the version you want to install

1.2 Create an Order in Server🔗

Order is an important step in the payment process.

  • An order should be created for every payment.
  • You can create an order using the Orders API. It is a server-side API call. Know how to authenticate Orders API.
  • The order_id received in the response should be passed to the checkout. This ties the Order with the payment and secures the request from being tampered.

API Sample Code🔗

The following code is add to OrderCreation.java and response for creating an order:

Copycurl -X POST https://api.razorpay.com/v1/orders -u <YOUR_KEY_ID>:<YOUR_SECRET> -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()); }
Copyimport razorpay client = razorpay.Client(auth=("api_key", "api_secret")) DATA = { "amount": 100, "currency": "INR", "receipt": "receipt#1", "notes": { "key1": "value3", "key2": "value2" } } client.order.create(data=DATA)
Copy$order = $client->order->create([ 'receipt' => 'order_rcptid_11', 'amount' => 50000, // amount in the smallest currency unit 'currency' => 'INR'// <a href="/docs/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_IluGWxBm9U8zJ8", "entity": "order", "amount": 50000, "amount_paid": 0, "amount_due": 50000, "currency": "INR", "receipt": "rcptid_11", "status": "created", "attempts": 0, "notes": [], "created_at": 1566986570 }

Request Parameters🔗

Here is the list of parameters and their description for creating an order:

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. Length must be 3 characters.
receipt optional
string Your receipt id for this order should be passed here. Maximum length 40 characters.
notes optional
json 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”.
partial_payment optional
boolean Indicates whether the customer can make a partial payment. Possible values:
  • true: The customer can make partial payments.
  • false (default): The customer cannot make partial payments.

Know more about Orders API.

Error Response Parameters🔗

The error response parameters are available in the API Reference Guide.

1.3 Add Checkout Options🔗

Add the Razorpay Checkout options in your project. For example, if you are using HTML for your frontend, create a page called index.jsp and add the Pay button on your web page using the checkout code, Handler Function or Callback URL.

Handler Function or Callback URL🔗

Handler Function

Callback URL

When you use this:

  • On successful payment, the customer is shown your web page.
  • On failure, the customer is notified of the failure and asked to retry the payment.

When you use this:

  • On successful payment, the customer is redirected to the specified URL, for example, a payment success page.
  • On failure, the customer is asked to retry the payment.

Copy<button id="rzp-button1">Pay</button> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "YOUR_KEY_ID", // Enter the Key ID generated from the Dashboard "amount": "50000", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "order_IluGWxBm9U8zJ8", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9999999999" }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick = function(e){ rzp1.open(); e.preventDefault(); } </script>
Copy<button id="rzp-button1">Pay</button> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "YOUR_KEY_ID", // Enter the Key ID generated from the Dashboard "amount": "50000", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "order_IluGWxBm9U8zJ8", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "callback_url": "https://eneqd3r9zrjok.x.pipedream.net/", "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9999999999" }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); document.getElementById('rzp-button1').onclick = function(e){ rzp1.open(); e.preventDefault(); } </script>

Handy Tips
If case you want to use this as your final code, follow the steps given below:

  • Edit the [KEY_ID] inside index.ftl. Use the test keys while testing your application.
    Know how to Generate API keys.

  • Edit the [KEY_ID] and [KEY_SECRET] in server.yml.

Checkout Options🔗

key mandatory

string API Key ID generated from the Razorpay Dashboard.

amount mandatory

integer The amount to be paid by the customer in currency subunits. For example, if the amount is ₹100, enter 10000.

currency mandatory

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

name mandatory

string The business name shown on the Checkout form.

description optional

string Description of the purchase item shown on the Checkout form. Must start with an alphanumeric character.

image optional

string Link to an image (usually your business logo) shown on the Checkout form. Can also be a base64 string, if loading the image from a network is not desirable.

order_id mandatory

string Order ID generated via Razorpay Orders API.

prefill

object You can prefill the following details at Checkout.

name optional
string Cardholder's name to be pre-filled if customer is to make card payments on Checkout.
email optional
string Email address of the customer.
contact optional
string Phone number of the customer. 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.
method optional
string Pre-selection of the payment method for the customer. Will only work if contact and email are also pre-filled. Possible values
  • card
  • netbanking
  • wallet
  • emi
  • upi
notes optional

object Set of key-value pairs that can be used to store additional information about the payment. It can hold a maximum of 15 key-value pairs, each 256 characters long (maximum).

theme

object Thematic options to modify the appearance of Checkout.

hide_topbar optional
boolean 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
  • false (default): Displays the top bar.
color optional
string Enter your brand colour's HEX code to alter the appearance of Checkout form.
backdrop_color optional
string Enter a HEX code to change the Checkout's backdrop colour.
modal

object Options to handle the Checkout modal.

backdropclose optional
boolean Indicates whether clicking the translucent blank space outside the Checkout form should close the form. Possible values are:
  • true: Closes the form when your customer clicks outside the checkout form.
  • false (default): Does not close the form when customer clicks outside the checkout form.
escape optional
boolean Indicates whether pressing the escape key should close the Checkout form. Possible values are:
  • true (default): Closes the form when the customer presses the escape key.
  • false: Does not close the form when the customer presses the escape key.
handleback optional
boolean Determines whether Checkout must behave similar to the browser when back button is pressed. Possible values:
  • true (default): 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.
  • false: Checkout does not simulate a back press when browser's back button is pressed.
confirm_close optional
boolean Determines whether a confirmation dialog box should be shown when customers attempt to close Checkout. Possible values:
  • true: Confirmation dialog box is shown.
  • false (default): Confirmation dialog box is not shown.
ondismiss optional
function Used to track the status of Checkout. You can pass a modal object with ondismiss: function(){} as options. This function is called when the modal is closed by the user.
animation optional
boolean Show an animation before loading of Checkout.
  • true(default): Animation appears.
  • false: Animation does not appear.
subscription_id optional

string If you are accepting recurring payments using Razorpay Checkout, you should pass the relevant subscription_id to the Checkout. Know more about Subscriptions on Checkout.

subscription_card_change optional

boolean Permit or restrict customer from changing the card linked to the subscription. You can also do this from the hosted page. Possible values:

  • true: Allow the customer to change the card from Checkout.
  • false (default): Do not allow the customer to change the card from Checkout.
recurring optional

boolean Determines if you are accepting recurring (charge-at-will) payments on Checkout via instruments such as emandate, paper NACH and so on. Possible values:

  • true: You are accepting recurring payments.
  • false (default): You are not accepting recurring payments.
callback_url optional

string Customers will be redirected to this URL on successful payment. Ensure that the domain of the Callback URL is whitelisted.

redirect optional

boolean Determines whether to post a response to the event handler post payment completion or redirect to Callback URL. callback_url must be passed while using this parameter. Possible values:

  • true: Customer is redirected to the specified callback URL in case of payment failure.
  • false (default): Customer is shown the Checkout popup to retry the payment.
customer_id optional

string Unique identifier of customer. Used for:

timeout optional

integer Sets a timeout on Checkout, in seconds. After the specified time limit, customer will not be able to use Checkout.

remember_customer optional

boolean Determines whether to allow saving of cards. Can also be configured via the Razorpay Dashboard. Possible values:

  • true: Enables card saving feature.
  • false (default): Disables card saving feature.
readonly

object Marks fields as read-only.

contact optional
boolean Used to set the contact field as readonly. Possible values:
  • true: Customer will not be able to edit this field.
  • false (default): Customer will be able to edit this field.
email optional
boolean Used to set the email field as readonly. Possible values:
  • true: Customer will not be able to edit this field.
  • false (default): Customer will be able to edit this field.
name optional
boolean Used to set the name field as readonly. Possible values:
  • true: Customer will not be able to edit this field.
  • false (default): Customer will be able to edit this field.
hidden

object Hides the contact details.

contact optional
boolean Used to set the contact field as optional. Possible values:
  • true: Customer will not be able to view this field.
  • false (default): Customer will be able to view this field.
email optional
boolean Used to set the email field as optional. Possible values:
  • true: Customer will not be able to view this field.
  • false (default): Customer will be able to view this field.
send_sms_hash optional

boolean Used to auto-read OTP for cards and net banking pages. Applicable from Android SDK version 1.5.9 and above. Possible values:

  • true: OTP is auto-read.
  • false (default): OTP is not auto-read.
allow_rotation optional

boolean Used to rotate payment page as per screen orientation. Applicable from Android SDK version 1.6.4 and above. Possible values:

  • true: Payment page can be rotated.
  • false (default): Payment page cannot be rotated.
retry optional

object Parameters that enable retry of payment on the checkout.

enabled
boolean Determines whether the customers can retry payments on the checkout. Possible values:
  • true (default): Enables customers to retry payments.
  • false: Disables customers from retrying the payment.
max_count
integer The number of times the customer can retry the payment. Recommended to set this to 4. Having a larger number here can cause loops to occur.
config optional

object Parameters that enable configuration of checkout display language.

display

object Child parameter that enables configuration of checkout display language.

language
string The language in which checkout should be displayed. Possible values:
  • en: English
  • ben: Bengali
  • hi: Hindi
  • mar: Marathi
  • guj: Gujarati
  • tam: Tamil
  • tel: Telugu

Handy Tips
The open method of Razorpay object (rzp1.open()) must be invoked by your site's JavaScript, which may or may not be a user-driven action such as a click.

Configure Payment Methods🔗

Multiple payment methods are available on Razorpay Standard Checkout.

  • The payment methods are fixed and cannot be changed.
  • You can configure the order or make certain payment methods prominent. Know more about configuring payment methods.

Handle Payment Success and Failure🔗

The way the Payment Success and Failure scenarios are handled depends on the Checkout Sample Code you used in the last step.

Checkout with Handler Function🔗

If you used the sample code with the handler function:

  • On Payment Success

The customer sees your website page. The checkout returns the response object of the successful payment (razorpay_payment_id, razorpay_order_id and razorpay_signature). Collect these and send them to your server.

  • On Payment Failure

The customer is notified about payment failure and asked to retry the payment. Know about the error parameters.

Success/Failure Handling Code (Checkout with Handler Function)🔗

Copy"handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature)}
Copyrzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }

Checkout with Callback URL🔗

If you used the sample code with the callback URL:

  • On Payment Success

Razorpay makes a POST call to the callback URL with the razorpay_payment_id, razorpay_order_id and razorpay_signature in the response object of the successful payment. Only successful authorisations are auto-submitted.

  • On Payment Failure

In case of failed payments, the checkout is displayed again to facilitate payment retry.

1.4 Store Fields in your Server🔗

A successful payment returns the following fields to the Checkout form.

  • You need to store these fields in 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.

1.5 Verify Payment Signature🔗

This is a mandatory step 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 Razorpay 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🔗

Given below are the sample codes for payment signature verification.

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' , 'razorpay_order_id' => '12122'); $order = $api->utility->verifyPaymentSignature($attributes)
Copyrequire 'razorpay' Razorpay.setup('key_id', 'key_secret') payment_response = { 'razorpay_order_id': '12122', 'razorpay_payment_id': '332', 'razorpay_signature': '23233' } Razorpay::Utility.verify_payment_signature(payment_response)
Copyimport razorpay client = razorpay.Client(auth=("YOUR_ID", "YOUR_SECRET")) client.utility.verify_payment_signature({ 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': razorpay_payment_id, 'razorpay_signature': razorpay_signature })
Copy Dictionary<string, string> attributes = new Dictionary<string, string>(); attributes.Add("razorpay_payment_id", paymentId); attributes.Add("razorpay_order_id", Request.Form["razorpay_order_id"]); attributes.Add("razorpay_signature", Request.Form["razorpay_signature"]); Utils.verifyPaymentSignature(attributes);
Copyvar { validatePaymentVerification } = require('./dist/utils/razorpay-utils'); validatePaymentVerification({"order_id": razorpayOrderId, "payment_id": razorpayPaymentId }, signature, secret);
Copyimport ( "crypto/hmac" "crypto/sha256" "crypto/subtle" "encoding/hex" "fmt" ) func main() { signature := "477d1cdb3f8122a7b0963704b9bcbf294f65a03841a5f1d7a4f3ed8cd1810f9b" secret := "qp3zKxwLZxbMORJgEVWi3Gou" data := "order_J2AeF1ZpvfqRGH|pay_J2AfAxNHgqqBiI" //fmt.Printf("Secret: %s Data: %s\n", secret, data) // Create a new HMAC by defining the hash type and the key (as byte array) h := hmac.New(sha256.New, []byte(secret)) // Write Data to it _, err := h.Write([]byte(data)) if err != nil { panic(err) } // Get result and encode as hexadecimal string sha := hex.EncodeToString(h.Sum(nil)) fmt.Printf("Result: %s\n", sha) if subtle.ConstantTimeCompare([]byte(sha), []byte(signature)) == 1 { fmt.Println("Works") } }

Post Signature Verification🔗

After you have successfully completed the integration, you can set up webhooks, make test payments, replace test key with live key and integrate with other APIs.

1.6 Verify Payment Status🔗

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

Verify Payment Status From Dashboard🔗

  1. Log into the Dashboard and navigate to Transactions → Payments.
  2. Check if a payment_ID has been generated and note the status. In case of a successful payment, the status is marked as captured.

Subscribe to Webhook events🔗

You can use Razorpay Webhooks to configure and receive notifications when a specific event occurs. When one of these events is triggered, we send an HTTP POST payload in JSON to the webhook's configured URL. Know how to set up Webhooks.

Example🔗

If you have subscribed to the order.paid webhook event, you will receive a notification every time a customer pays you for an order.

Poll APIs🔗

Poll Payment APIs to check the payment status.

×