Integrating RazorPay in Your Flutter App : An Ultimate Guide [2021]

Razorpay is one the fastest growing payment gateway platforms and is easily integrated into Flutter. It allows users to simply accept, process and disburse payments with ease. Specific flutter plugin makes it easy to use within all flutter applications. This acts as a wrapper around the native Android and iOS SDKs.

Razorpay is mainly used in India and the majority of its clients include small businesses having 1M-10M dollars revenue. It has a market share of 1.79%. Few companies currently using it are Spicejet, BookMyShow, Nykaa, Urbanclap, Zoho, Zomato, Goibibo and many more. 

Razorpay provides products for every payment need. Be it the payment button, payment links, cash-out, subscriptions, auto-pay UPI, it has a solution for all. It comes with easy activation and economic pricing.

Recently, we integrated Razorpay for one of our clients – CabbyLal – A Taxi Booking App. Using Razorpay made the process of payment integration in flutter application development simple, quick and easily testable.

Here is the step by step guide for integrating Razorpay in flutter:

Setting up and generating the API key

  • Create a Razorpay account and log in to the dashboard.
  • Select the mode (Test – for testing purpose or Live – for production environments) for which you want to generate the API key.
  • Navigate to SettingsAPI KeysGenerate Key to get the key for the chosen mode.

Installation and importing package

razorpay_flutter: 1.1.0 
  • Run – flutter packages get within the root directory of your app.
  • Import package by adding the below code
import 'package:razorpay_flutter/razorpay_flutter.dart';

Creating an instance and handling events

  • Use the below code to make a Razorpay instance.
_razorpay = Razorpay();

Events and handlers

  • The Razorpay flutter plugin uses event-based communication and emits events when payments fail or succeed. The event names are exposed via the constants from the Razorpay class
EVENT_PAYMENT_SUCCESS The payment was successful
EVENT_PAYMENT_ERROR The payment was not successful
EVENT_EXTERNAL_WALLET The external wallet was selected for payment

Use the on(String event, Function handler) method on the Razorpay instance to connect event listeners.

void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
 }
  • Define the handlers in the class to handle different responses
Future<void> _handlePaymentSuccess(PaymentSuccessResponse response) async {
    UiUtils.showToast("SUCCESS: ", false);
    String paymentId = response.paymentId;
    PaymentViewModel paymentViewModel = Provider.of(context, listen: false);

    PaymentModel paymentModel = await paymentViewModel.confirmPayment(
        bookingId, paymentMode, paymentId);

    if (paymentModel != null) {
      if (paymentModel.success == 1) {
        UiUtils.showToast(paymentModel.message, false);
        Navigator.pushNamedAndRemoveUntil(
            context, "/bookingvisit", (route) => false);
      } else {
        UiUtils.showToast(paymentModel.message, true);
      }
    }
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    Fluttertoast.showToast(
        msg: "ERROR: " + response.code.toString() + " - " + response.message,
        timeInSecForIos: 4);
    print(response.toString());
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    Fluttertoast.showToast(
        msg: "EXTERNAL_WALLET: " + response.walletName, timeInSecForIos: 4);
    print(response.toString());
  }
  • To clear event listeners, use the clear method on the Razorpay instance.
_razorpay.clear(); // Removes all listeners

Checkout option settings

  • Fill the details along with key as shown in the below code:
void openCheckout(double totalAmount) async {
    var options = {
      'key': UiUtils.paymentKey,
      'amount': totalAmount * 100,
      'name': _name,
      'description': _description,
      'prefill': {'contact': ‘9999999999’, 'email':’test@gmail.com’},
      'external': {
        'wallets': ['paytm']
      }
    };

    try {
      _razorpay.open(options);
    } catch (e) {
      debugPrint(e);
    }
  }

Payment Success Response:

  • Payment Id: Data Type – string : The ID for the payment.
  • Order Id:  Data Type – string : order ID if the payment was for an order, otherwise null.
  • Signature: Data Type – string : The signature to be used for payment verification. Only valid for orders, otherwise null.

Payment Failure Response:

  •  Code: integer The error code.
  • Message: string The error message.

External Wallet Response:

  • Wallet Name: Data type – string : The name of the external wallet selected.

Here are the final sample screenshots of the Razorpay payment gateway integration in flutter application.