Card and UPI supported Razorpay.js Integration with Chargebee APIs

Watch Video

Tutorial Scope 

This tutorial helps implement Card or UPI(mandates) payments using Razorpay.js and Chargebee APIs. We have also included the example code and Github links to it. This way, you can try out the tutorial with the mock checkout.

These steps are explained in the sections that follow.

  • Estimate the amount to be charged using Chargebee's Estimate API.
  • Create a customer in Razorpay Gateway Server Side.
  • Create an order in Razorpay Gateway Server Side.
  • Use the order ID and customer ID in Razorpay.js and construct the checkout page.
  • Razorpay JS will return a payment ID from Razorpay, and use the payment ID as payment_intent[gw_token] to create the subscription.
Note
  • It is mandatory to use the Chargebee API  to complete the Razorpay.js Integration.
  • This tutorial helps you integrate recurring UPI(mandates) and Card payments with Chargebee API. We do not recommend Razorpay JS to integrate recurring Netbanking(mandates) payments with Chargebee APIs. To integrate recurring Netbanking(mandates) payments with Chargebee APIs use Chargebee JS's Bank payments using helper  > Integrate Netbanking.

Razorpay.js: Overview 

Razorpay has developed the Standard Checkout method that can configure payment methods, orders, company logos, and also select custom colors based on your preference. Read more .

Prerequisites 

Setup the following before starting the integration process.

  • Razorpay's server-side requirements.

    • Create  a Razorpay account and integrate  it with your Chargebee user interface.
    • Generate the test API key  on Razorpay's dashboard.
  • Razorpay's client-side requirements.

    • Import checkout.js in HTML -
      <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
      
    • Follow these steps  to create a checkout page.
  • Download and import  Chargebee's client library of your choice. Configure the client library with the Chargebee Test site and its full-access API Key .

    Configuring Site Credential: Sample Code Snippet to set the environment for calling the Chargebee API. You need to sign up at the Chargebee app to get this credential.

Integrate Razorpay.js with Chargebee APIs 

To integrate Razorpay.js with Chargebee APIs, follow these steps.

  1. Retrieve the estimated details of the purchase using Chargebee's Estimate API .

    curl  https://{site}.chargebee.com/api/v2/customers/__test__8aspfRrLYZEd2/create_subscription_for_items_estimate \
     -X POST  \
     -u {site_api_key}:\
     -d subscription_items[item_price_id][0]="basic-INR" \
     -d subscription_items[billing_cycles][0]=2 \
     -d subscription_items[quantity][0]=1
    

    Note: Before retrieving the estimated details create a customer , item family , and item  to pass customer_id and item_price_id in Chargebee's Estimate API.

  2. Create a customer in Razorpay using API .

    curl -u [YOUR_KEY_ID]:[YOUR_KEY_SECRET] \
         -X POST https://api.razorpay.com/v1/customers \
         -H "Content-Type: application/json" \
         -d '{
            "name":"Gaurav Kumar",
             "contact":"9123456780",
             "email":"[email protected]"
             }'
    
  3. Create order in Razorpay with the estimated amount using Razorpay API . Use specific order API for recurring UPI (mandates) and card  payments and pass the relevant values to the token parameter.

    curl -X POST https://api.razorpay.com/v1/orders 
         -U [YOUR_KEY_ID]:[YOUR_KEY_SECRET]
         -H 'content-type:application/json'
         -d '{
              "amount":2400,
              "currency":"INR",
              "payment_capture":"0",
              "receipt":"Receipt No. 1",
              "token":{
                "max_amount":5000,
                "expire_at":2709971120,
                "frequency":"monthly"
              },
              "customer_id": "cust_JDHT4nOke37JCy"
             }'
    
  4. Create a payment button  for initiating the checkout.

    <button id="rzp-button1">Pay</button>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <script>var options = { checkout options }</script>
    
  5. Create a Razorpay instance using the checkout options  by adding it to the above script using the handler function or using the callback URL.

    Using Handler Function

    {
      key: "", // Enter the Key ID generated from the Dashboard
      amount: "2400", // 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_JDHTaJjAJsLN0k", //This is a sample Order ID. Pass the `order_id` obtained from the response of order creation in Razorpay.
      handler: function (response) {
          alert(response.razorpay_payment_id); //This is a payment ID that has to be used during subscription creation in Chargebee.
      },
      customer_id: "cust_JDHT4nOke37JCy", //This is a sample Customer ID. Pass the value of `customer_id` obtained from the response of customer creation in Razorpay.
      prefill: {
          name: "Gaurav Kumar",
          email: "[email protected]",
          contact: "9999999999",
      },
      notes: {
          address: "Razorpay Corporate Office",
      },
      theme: {
          color: "#3399cc",
      }
    }
    

    Using Callback URL

    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": "[email protected]",
        "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();
    }
    
  6. In Razorpay checkout retrieve the payment ID from the response of the handler function  or callback URL .

    handler: function (response) 
    { 
    alert(response.razorpay_payment_id); //This is a payment ID that has to be used during subscription creation in Chargebee. 
    }
    
  7. To create a subscription in Chargebee, pass the value of response.razorpay_payment_id(payment ID) in payment_intent[gw_token] , using the create subscription API . You can pass this payment ID value to any endpoint supporting 3DS. Read more .

    Sample request for creating a subscription using a card

    curl http://{site}.chargebee.com/api/v2/customers/gaurav_kumar/subscription_for_items \
     -X POST  \
     -u {site_api_key}:\
     -H 'Content-Type: application/x-www-form-urlencoded' \
     -d 'subscription_items[item_price_id][0]=cbdemo-INR-Yearly' \
     -d 'subscription_items[billing_cycles][0]=2' \
     -d 'subscription_items[quantity][0]=1' \
     -d 'payment_intent[gateway_account_id]=gw_AzqMB5T4qqHso7xk' \
     -d 'payment_intent[gw_token]=pay_JTXzw2z5Zuyl3Q' \
     -d 'payment_intent[payment_method_type]=card'
    

    Note: Refer to the table  contains detailed information on the expected input format for each payment method and data to be passed to the respective Chargebee parameters.

Though the parameters have been validated at the client-side, for additional security, it is strongly recommended that you perform these validations on the server-side as well.

Chargebee Response

After the request for subscription creation is made, Chargebee returns a success or failure(error) response.

The following are the responses.

  • Chargebee returns a successful response in the JSON format wrapped in the client library's 'result' class. In case of successful checkout, you can redirect the user to a page with a "Thank You" message.

  • In case of an error, Chargebee returns an error response, which is an exception thrown by the client library.

Validation and Error-Handling 

Here's how we validate user inputs and handle API call errors in this demo:

  • Client-Side Validation: Chargebee uses the jQuery form validation plugin to verify whether the user's field inputs(email, zip code, and phone number) are valid or invalid.

  • Server-Side Validation: As this is a demo application, we skipped the server-side validation for all input parameters. However, we recommend you perform the validation at your end.

  • Payment Errors: If a payment fails due to processing errors, Chargebee returns an error response as a payment exception by the client library. Exceptions are handled in the demo application with appropriate error messages.

  • General API Errors: Chargebee might return error responses for various reasons such as invalid configuration, bad requests, etc. To identify specific reasons for all error responses, you can check the API documentation. Also, take a look at the error handler file to check how these errors can be handled.

Test Cards

When you have successfully integrated all the above steps for card payment, test your integration with some test transactions. Here are some credit card numbers that you can use to test the application:

 Card Network   Card Type   Card Number   CVV   Expiry Date 
 VISA   Credit Card   4718 6091 0820 4366   Random CVV   Any future date 

For details, read more .

Test UPI

When you have successfully integrated all the above steps for UPI(mandates) payment, test your integration with some test transactions. To use the test UPI ID details:

  • At the Checkout, select UPI(mandates) as the payment method.
  • Enter the UPI ID.
  • Enter a random UPI pin if required.

For details, read more .