Razor Pay is one of the best payment gateways which is used by many companies. It provides many payment options such as Card, Netbanking, External Wallets, UPI, etc.
First of all, we need to create an account on Razorpay (https://razorpay.com/). We require an API key for making payment checkout call in our flutter application and to generate an API key follow the steps:
- Sign in to the Razorpay dashboard using the login credential.
- Select one of the modes(Test or Live) for which you need to create the API key.
- You can get your key under Settings>API keys.
Note: You need to produce separate API Keys for the test and live modes. You’re not charged while making payment in test mode.
Now move to flutter project setup,
Implementation:
Step 1: Add the dependencies
Add dependencies to pubspec.yaml file.
razorpay_flutter: ^1.1.0
Step 2: Import package
import 'package:razorpay_flutter/razorpay_flutter.dart';
Minimum Version Requirement:
For Android, guarantee that the base minimum API level for your app is 19 or higher.(Need to change minSdkVersion to 21 in app level build,gradle)
For iOS, guarantee that the base minimum deployment target for your app is iOS 10.0 or higher.Likewise, remember to enable bitcode for your project.(Set it in Xcode)
Step 3: Run flutter packages get
in the root directory of your app.
Now you’ve to put some effort to make it work in your application.
Create Razorpay instance:
To create Razorpay instance add this to your code
Razorpay _razorpay;
Set Event Listeners:
The event names are revealed via the constants,
EVENT_PAYMENT_SUCCESS
,EVENT_PAYMENT_ERROR
,and
EVENT_EXTERNAL_WALLET
from the Razorpay class.
Use the
on(String event, Function handler)
method on the Razorpay instance to attach event listeners.
Add these listeners in initState method :
@override 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); }
Event 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.
Handler:
The handlers would be defined in the class and handle the different responses and you can handle the response according to your taste like using toast, snack bar, or dialog.
Here I used fluttertoast for that:
void _handlePaymentSuccess(PaymentSuccessResponse response) { Fluttertoast.showToast( backgroundColor: Colors.deepPurple[300], fontSize: 13, textColor: Colors.black, msg: "Order SUCCESS: " + response.paymentId, toastLength: Toast.LENGTH_SHORT); } void _handlePaymentError(PaymentFailureResponse response) { Fluttertoast.showToast( backgroundColor: Colors.red[400], fontSize: 13, textColor: Colors.black, gravity: ToastGravity.TOP, msg: "ERROR: " + response.code.toString() + " - " + response.message, toastLength: Toast.LENGTH_SHORT); } void _handleExternalWallet(ExternalWalletResponse response) { Fluttertoast.showToast( backgroundColor: Colors.green[400], fontSize: 13, textColor: Colors.black, gravity: ToastGravity.TOP, msg: "Paid By: " + response.walletName, toastLength: Toast.LENGTH_SHORT); }
To clear event listeners, use the
clear
method on the Razorpay instance.
_razorpay.clear(); // Removes all listeners
Let’s make payment on checkout:
We just need to pass the option as a parameter in the open method on the Razorpay instance shown as bellow:
void openCheckout() async { var options = { 'key': 'rzp_test_DRfVxaEbtFkklr', 'amount': 28000, //in the smallest currency sub-unit. 'name': 'Acme Corp.', 'description': 'Tulsi Mala', 'timeout': 60, // in seconds 'prefill': {'contact': '9523616123', 'email': 'wallet@razor.com'} }; try { _razorpay.open(options); } catch (e) { debugPrint('Error: e'); } }
import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:razorpay_flutter/razorpay_flutter.dart'; class Home extends StatefulWidget { const Home({Key key}) : super(key: key); @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { Razorpay _razorpay; @override void initState() { super.initState(); // create razorpay instace _razorpay = Razorpay(); _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess); _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError); _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet); } @override void dispose() { super.dispose(); _razorpay.clear(); } // for product checout void openCheckout() async { var options = { 'key': 'rzp_test_DRfVxaEbtFkklr', 'amount': 28000, //in the smallest currency sub-unit. 'name': 'Acme Corp.', 'description': 'Tulsi Mala', 'timeout': 60, // in seconds 'prefill': {'contact': '9523616123', 'email': 'wallet@razor.com'} }; try { _razorpay.open(options); } catch (e) { debugPrint('Error: e'); } } // Event handlers void _handlePaymentSuccess(PaymentSuccessResponse response) { Fluttertoast.showToast( backgroundColor: Colors.deepPurple[300], fontSize: 13, textColor: Colors.black, msg: "Order SUCCESS: " + response.paymentId, toastLength: Toast.LENGTH_SHORT); } void _handlePaymentError(PaymentFailureResponse response) { Fluttertoast.showToast( backgroundColor: Colors.red[400], fontSize: 13, textColor: Colors.black, gravity: ToastGravity.TOP, msg: "ERROR: " + response.code.toString() + " - " + response.message, toastLength: Toast.LENGTH_SHORT); } void _handleExternalWallet(ExternalWalletResponse response) { Fluttertoast.showToast( backgroundColor: Colors.green[400], fontSize: 13, textColor: Colors.black, gravity: ToastGravity.TOP, msg: "Paid By: " + response.walletName, toastLength: Toast.LENGTH_SHORT); } // build mehod @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Dashboard'), ), body: GridView.builder( padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10), shrinkWrap: true, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( childAspectRatio: 0.9, crossAxisCount: 1, crossAxisSpacing: 20, mainAxisSpacing: 20), itemCount: 1, itemBuilder: (context, index) { return GestureDetector( child: Container( decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.deepPurple[50], offset: Offset(0, 3), blurRadius: 3.0, spreadRadius: 3.0), ], borderRadius: BorderRadius.circular(10)), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: [ Expanded( child: ClipRRect( borderRadius: BorderRadius.vertical(top: Radius.circular(10)), child: Image.asset( "assets/image/item.jpg", fit: BoxFit.fill, width: double.infinity, ), ), ), SizedBox( height: 5, ), Padding( padding: EdgeInsets.only(left: 5, right: 5), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( // height: 30, child: Text( "Tulsi Mala", style: TextStyle( color: Colors.deepPurple, fontSize: 15, fontWeight: FontWeight.w500), maxLines: 2, overflow: TextOverflow.ellipsis, ), ), SizedBox( height: 5, ), RichText( maxLines: 1, softWrap: true, text: TextSpan( text: "₹ 280.00 ", style: TextStyle( color: Colors.deepPurple, ), children: [ TextSpan( text: "₹ 310.00", style: TextStyle( color: Colors.red, fontSize: 12, decoration: TextDecoration.lineThrough)) ]), ), SizedBox( height: 5, ), Row( children: [ Expanded( child: RatingBar.builder( initialRating: 3, minRating: 1, direction: Axis.horizontal, itemSize: 15, allowHalfRating: true, itemCount: 5, tapOnlyMode: true, onRatingUpdate: (rating) { print(rating); }, itemBuilder: (context, _) => Icon( Icons.star, color: Colors.deepPurple[300], ), ), ), ], ), ], ), ), SizedBox( height: 5, ), Center( child: MaterialButton( onPressed: () { openCheckout(); }, child: Text( "Check Out", style: TextStyle(color: Colors.white, fontSize: 18), ), color: Colors.deepPurple[300], elevation: 2, ), ), SizedBox( height: 5, ), ], ), ), ); })); } }
This is a small shopping flutter example that will integrate Razorpay payment, in this code, you will see how to add Razorpay to our code and how to get an order with online payment. The below video shows how Razorpay Payment will work.
You can see all orders made with this under the transaction section of the Razorpay dashboard and can take action according to payment status.
That’s it will meet in next article.
You’re looking for resources….
Here it is : https://github.com/Mehul-vision/razorpay_demo1
Good article