Mastering RazorPay Payment Gateway in Flutter

Posted By : Kamlesh Pandey | 28-Jan-2021

Razorpay In Flutter

 

Mastering Razorpay

 

Razor Pay is one of the best payment gateways in flutter apps up till now. Going digital everywhere now digital payments are present for almost every product and service. Having Payments facility in apps now is not just only a fashion now it's the convenient fashion it's the demand of the current era. There exist many other payments too in flutter but we would be using Razorpay in today's blog, as it also has the most updated plugin in pub.dev. So let's start and implement it in around 15 min. Let's master the Razorpay in Flutter.

 

How Our App Will Show Up?

 

Also Read: Xamarin is Dead, Long Live MAUI

 

Generate API Key:

 

  1. Sign in to your Dashboard using the credentials.

  2. Choose the mode (Test or Live) for which you want to create the API key. Here, we are using the test mode API key.

  3. Go to SettingsAPI KeysGenerate Key to create a key for the chose mode.

 

Step1: Add the Dependencies

 

Add dependencies to pubspec.yaml file.

 

dependencies:

razorpay_flutter: ^1.2.3
Run flutter packages get in the root directory of your app.

 

Add Proguard Rules (Android Only)


-keepattributes *Annotation*
-dontwarn com.razorpay.**
-keep class com.razorpay.** {*;}
-optimizations !method/inlining/
-keepclasseswithmembers class * {
  public void onPayment*(...);
}

Add the following lines to the Proguard files, if you are using Proguard for your builds.

 

Also Read: Understanding The Concept Of AMP Pages

 

Step2: Import


import 'package:razorpay_flutter/razorpay_flutter.dart';

 

Minimum Version Requirement:

 

  • For Android, the minimum API level for your app should be 19 or higher.
  • For iOS, the minimum deployment target for your app should be iOS 10.0 or higher. Also, don't forget to enable bitcode for your project.


Step3: Razorpay Instance :

 

razorpay = new Razorpay();

Event Listeners :

 

The plugin exercises event-based communication. It emits events once payments fail or succeed.

The following constants expose the event name: EVENT_PAYMENT_SUCCESSEVENT_PAYMENT_ERROR and EVENT_EXTERNAL_WALLET from the Razorpay class.

To attach event listeners, use the on(String event, Function handler) method on the Razorpay instance.

razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, handlerPaymentSuccess);
razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, handlerErrorFailure);
razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, handlerExternalWallet);

 

Handlers : 

 

void handlerPaymentSuccess(PaymentSuccessResponse response) {
  print("Pament success");
  msg = "SUCCESS: " + response.paymentId;
  showToast(msg);
}

void handlerErrorFailure(PaymentFailureResponse response) {
  msg = "ERROR: " + response.code.toString() + " - " + jsonDecode(response.message)['error']['description'];
  showToast(msg);
}

void handlerExternalWallet(ExternalWalletResponse response) {
  msg = "EXTERNAL_WALLET: " + response.walletName;
  showToast(msg);
}

 

Clear Event Listeners :

 

razorpay.clear();

 

Step4: Checkout Options :

 

var options = {
  "key": "Use Your API Key Id here",
  "amount": num.parse(textEditingController.text) * 100, // Convert Paisa to Rupees
  "name": "Test Payment By Kamlesh",
  "description": "This is a Test Payment",
  "timeout": "180",
  "theme.color": "#03be03",
  "currency": "INR",
  "prefill": {"contact": "2323232323", "email": "testByKamlesh@razorpay.com"},
  "external": {
    "wallets": ["paytm"]
  }
};

 

All the other checkout Form Fields can be used for more customization/requirements.  All Checkout Form Fields.

 

Also Read: Integrate JITSI Plugin In a Flutter Mobile Application

 

Step4: Open Razorpay Checkout :

 

razorpay.open(options);

 

Now You Can Store fields in the server from the success response. 

 

 

****** Responses ******

Payment Success Response :

  • Payment Id:  string The ID for the payment.
  • Order Id:  string The order ID for payment of an order, else null.
  • Signaturestring  The signature to be used for verifying the payment. Only valid for orders, otherwise null.

 

Payment Failure Response :

  • Codeinteger The error code.
  • Message: string The error message.

 

External Wallet Response :

Wallet Namestring The name of the external wallet selected.

 

****** Error Codes ******

The error codes have been uncovered as integers by the Razorpay class.

The code field of the PaymentFailureResponse the instance passed to the callback makes the error code accessible.

 

  1. NETWORK_ERROR: There was a network error. For example, loss of internet connectivity.
  2. INVALID_OPTIONS: An issue with options passed in Razorpay.open.
  3. PAYMENT_CANCELLED: The user canceled the payment.
  4. TLS_ERROR: TLS v1.1 or TLS v1.2 is not supported by the device.
  5. UNKNOWN_ERROR: An unknown error occurred.

****** Events Names ******

The event names have been uncovered as strings by the Razorpay class.

> EVENT_PAYMENT_SUCCESS: The payment was successful.

> EVENT_PAYMENT_ERROR: The payment was not successful.

> EVENT_EXTERNAL_WALLET: An external wallet was selected. 

 

****** Test Cards ******

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

 

Card Network

Domestic / International

Card Number

Mastercard

Domestic

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

 

****** Bonous ******

You generate your own unique order id Create your order in Server
Orders API restricts the possibility of multiple payments by binding a single successful payment to order. This can be passed in Checkout Options Given above  Orders_API

 

Also Read: Understanding The Lifecycle of Custom View In Android

 

****** Complete Code File ******

 

 

pubsec.yaml

cupertino_icons: ^0.1.3
razorpay_flutter: ^1.2.3
fluttertoast: ^7.1.6

 

main.dart

import 'package:flutter/material.dart';
import 'package:flutterrazorpayintegration/Home.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // primarySwatch: Colors.deepPurple,
        primarySwatch: Colors.deepPurple,
      ),
      home: Home(),
    );
  }
}

 Home.dart

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
import 'package:fluttertoast/fluttertoast.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Razorpay razorpay;
  TextEditingController textEditingController = new TextEditingController();
  FocusNode textFocusController = FocusNode();
  var msg;

  @override
  void initState() {
    super.initState();

    razorpay = new Razorpay();

    razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, handlerPaymentSuccess);
    razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, handlerErrorFailure);
    razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, handlerExternalWallet);
  }

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

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => textFocusController.unfocus(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text("Razor Pay"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 200,
                child: TextField(
                  focusNode: textFocusController,
                  cursorRadius: Radius.zero,
                  textAlign: TextAlign.center,
                  controller: textEditingController,
                  decoration: const InputDecoration(hintText: "Amount",),
                  style: const TextStyle(fontSize: 35.0),
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              Container(
                height: 50,
                child: RaisedButton(
                  color: Colors.deepPurple,
                  child: Text(
                    "Pay",
                    style: const TextStyle(color: Colors.white,fontSize: 30),
                  ),
                  onPressed: () {
                    openCheckout();
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  void openCheckout() {
    var options = {
      "key": "Use Your API Key Id here",
      "amount": num.parse(textEditingController.text) * 100, // Convert Paisa to Rupees
      "name": "Test Payment By Kamlesh",
      "description": "This is a Test Payment",
      "timeout": "180",
      "theme.color": "#03be03",
      "currency": "INR",
      "prefill": {"contact": "2323232323", "email": "testByKamlesh@razorpay.com"},
      "external": {
        "wallets": ["paytm"]
      }
    };

    try {
      razorpay.open(options);
    } catch (e) {
      print(e.toString());
    }
  }

  void handlerPaymentSuccess(PaymentSuccessResponse response) {
    print("Pament success");
    msg = "SUCCESS: " + response.paymentId;
    showToast(msg);
  }

  void handlerErrorFailure(PaymentFailureResponse response) {
    msg = "ERROR: " + response.code.toString() + " - " + jsonDecode(response.message)['error']['description'];
    showToast(msg);
  }

  void handlerExternalWallet(ExternalWalletResponse response) {
    msg = "EXTERNAL_WALLET: " + response.walletName;
    showToast(msg);
  }

  showToast(msg){
    Fluttertoast.showToast(
      msg: msg,
      toastLength: Toast.LENGTH_LONG,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.grey.withOpacity(0.1),
      textColor: Colors.black54,
    );
  }

}


Thanks for reading. Now you would have Mastered up to 95% of the Razorpay concepts for a flutter. Feeling Confident enough now. Yeah, that's what this post was meant to be.

 

By Kamlesh Pandey

Thank You.

 

Turn To Our SaaS Web And Mobile App Development Services

 

We are a SaaS application development company that provides end-to-end mobile app development services with a focus on cutting-edge technologies. Our development team uses JavaScript tools like Angular, Node, and ReactJS to make it adaptable, responsive, and include rich web applications to address different business prerequisites. We have an experienced team of Full Stack engineers that are skilled at performing both frontend and backend assignments. Our SaaS app development services address your project requirements by developing user-friendly apps that are easy to scale.

About Author

Author Image
Kamlesh Pandey

Kamlesh has an ample amount of knowledge in Cross-Platform mobile application development. Being very dedicated towards his work & Having a very good understanding of flutter, he is a great one to have in one's team.

Request for Proposal

Name is required

Comment is required

Sending message..