Integrating Razorpay In Flutter !!!

Integrating Razorpay In Flutter !!!

In this blog, you will learn how to integrate Razorpay into Flutter. From this blog, you will get everything you need to Integrate Razorpay into your Flutter Application.

Why Razorpay???

Because Razorpay is the only company in India that allows your business to accept, process, and disburse payments. Razorpay is developed in India, this is also a reason to use it and integrate it into our app.

Lets Start,

First of all, I will create a new Flutter application. This is the code of my new Flutter Application.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Razorpay',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Integrating Razorpay in Flutter'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, @required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _amountcontroller = new TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              TextField(
                controller: _amountcontroller,
                decoration: InputDecoration(
                    hintText: "Amount",
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10))),
              ),
              MaterialButton(
                minWidth: double.infinity,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
                onPressed: () {},
                child: Text(
                  "PAY",
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.blue,
              ),
            ],
          ),
        ));
  }
}

It looks like this,

Now it's time to introduce the package which you will need to use Razorpay in your app.

razorpay_flutter: ^1.2.7

Now add this package to pubspec.yaml file of your project under dependencies. After adding the package to pubspec.yaml file.

Now run the flutter pub get command, by this command flutter will install this dependency to your project.

Now to use this package in our application we have to import this package to our code file.

import 'package:razorpay_flutter/razorpay_flutter.dart';

Add this import statement at the top of your main.dart file.

Now we have to create an instance of Razorpay class provided by the package.

Razorpay _razorpay;

After creating an instance of the Razorpay class now we have to use it to make different handlers for different situations.

We will create our handlers in the initState() of our app so that when the app loads our screen the first method which is going to be called is the initState() and our Razorpay handlers will be ready with us for further use.

 @override
  void initState() {
    super.initState();
    _razorpay = new Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _paymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _paymentError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _externalWalletPayment);
  }

These are the 3 handlers which we will use, lets see them one by one

Razorpay.EVENT_PAYMENT_SUCCESS

It is called when the payment is successful and we have made a method which will be called when payment is successful i.e. _paymentSuccess.

Razorpay.EVENT_PAYMENT_ERROR

It is called when an error has occurred and we have made a method which will be called when an error has occurred in the payment i.e. _paymentError.

Razorpay.EVENT_EXTERNAL_WALLET

It is called when we have used an external wallet for payment and we have made a method which will be called when we use an external wallet for the payment i.e. _externalWalletPayment.

Here is the code for all three handlers.

Future<dynamic> _paymentSuccess(PaymentSuccessResponse response) {
    return showDialog(context: context, builder: (context) => dialog("Payment Successful", "Payment Id: ${response.paymentId}" ));
  }

  Future<dynamic> _paymentError(PaymentFailureResponse response) {
    return showDialog(context: context, builder: (context) => dialog("Error Occurred", " Error Code: ${response.code}  Payment Id: ${response.message}" ));
  }

  Future<dynamic> _externalWalletPayment(ExternalWalletResponse response) {
    return showDialog(context: context, builder: (context) => dialog("External Wallet Used", "Wallet Name: ${response.walletName}"));
  }

  Widget dialog(String title, String content){
    return AlertDialog(
      title: Flexible(child: Text("Wallet Used : " + title)),
      content: Flexible(child: Text(content)),
    );
  }

Now we will be moving forward and see how to open Razorpay and do the payment using it.

We will be creating a function called initiateRazorpay() which will be called when we press the PAY button in the app.

This is the code for the initiateRazorpay() method,

void initiateRazorpay() {
    Map<String, dynamic> options = {
      'key': 'Your Key Id',
      'amount': int.parse(_amountController.text) * 100,
      'name': 'Buy T shirt',
      'description': 'Shopping',
      'prefill': {'contact': '9898989898', 'email': 'priyanshu@gmail.com'},
      'external': {
        'wallets': ['paytm']
      }
    };
    try{
      _razorpay.open(options);
    }
    catch(e){
      print(e);
    }
  }

Here in this inititateRazorpay method, we have a map which is having all the data like key which is the key Id which you will get from Razorpay. It is the test Key Id which you will use in the development and testing phase of your application.

Next, there is the amount which is the amount which we are paying using Razorpay.

And all other data is understandable by you because it is the basic information you are giving in the Razorpay console.

After this now if we are initiating the Razorpay process when the app starts so we have to also stop it when the app stops or we are not using the app.

So for that, we have a method in flutter which is called when we come out of the app or that screen in which you were present in the app.

It is dispose()

This is the code for the dispose() method

 @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _razorpay.clear();
  }

Here we use _razorpay.clear() to clear the instance of Razorpay used.

Now you have all the things which you need to integrate Razorpay in Flutter.

Here is a video If you want to see how this app work

Full code:

import 'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';

void main() {
  runApp(MyApp());
}

  class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Razorpay',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Integrating Razorpay in Flutter'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, @required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _amountController = new TextEditingController();
  Razorpay _razorpay;

  @override
  void initState() {
    super.initState();
    _razorpay = new Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _paymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _paymentError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _externalWalletPayment);
  }

  Future<dynamic> _paymentSuccess(PaymentSuccessResponse response) {
    return showDialog(context: context, builder: (context) => dialog("Payment Successful", " Payment Id: ${response.paymentId}" ));
  }

  Future<dynamic> _paymentError(PaymentFailureResponse response) {
    return showDialog(context: context, builder: (context) => dialog("Error Occurred", " Error Code: ${response.code}  Payment Id: ${response.message}" ));
  }

  Future<dynamic> _externalWalletPayment(ExternalWalletResponse response) {
    return showDialog(context: context, builder: (context) => dialog("External Wallet Used", "Wallet Name: ${response.walletName}"));
  }

  Widget dialog(String title, String content){
    return AlertDialog(
      title: Flexible(child: Text(title)),
      content: Flexible(child: Text(content)),
    );
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _razorpay.clear();
  }

  void initiateRazorpay() async{
    Map<String, dynamic> options = {
      'key': 'Your Key Id',
      'amount': int.parse(_amountController.text) * 100,
      'name': 'Buy T shirt',
      'description': 'Shopping',
      'prefill': {'contact': '9898989898', 'email': 'priyanshu@gmail.com'},
      'external': {
        'wallets': ['paytm']
      }
    };
    try{
      _razorpay.open(options);
    }
    catch(e){
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              TextField(
                controller: _amountController,
                decoration: InputDecoration(
                    hintText: "Amount",
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10))),
              ),
              MaterialButton(
                height: 50,
                minWidth: double.infinity,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
                onPressed: () {
                  initiateRazorpay();
                },
                child: Text(
                  "PAY",
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.blue,
              ),
            ],
          ),
        ));
  }
}

Please share your thoughts in the comments. I am new to blogging so, please if there are any mistakes then please comment and point them out. Thank you!!!

If you want to connect these are my profiles

LinkedIn :- linkedin.com/in/priyanshupaliwal078 Github :- github.com/Priyanshu078