Introduction
Hi friends !! Are you looking for payment gateway integration in your future or existing Flutter App? If yes, this article is surely good for you. When we talk about payment gateway integration then, most people's first choice is the Razorpay Payment gateway because of its popularity and provides good documentation. In this article, we are going to implement the Razorpay payment gateway in Flutter. Using Razorpay, we can make payments using credit cards, debit cards, net banking, wallet, and UPI payments.
Razorpay Payment gateway is accepted by many popular companies such as,
Prerequisite
- Having a basic knowledge of Flutter
- Having the latest version of android studio
- Having a Razorpay account
How to create a Razorpay account?
Please follow the below steps to create a Razorpay account.
Step 1. Register with Razorpay
Please visit https://razorpay.com/ and register yourself.
Step 2. Generate API Key
After registering yourself now, go to Dashboard->Account & Settings->Account and product settings->Website and app settings, and now click on API keys.
Step 3. Now click on Generate Test Key and generate your API Key
Since I have already generated the key_id and key_secret, that's why the regenerate option is shown in my account. Please save the key_id and key_secret for further use.
Let's Start With Android Studio
Please follow the below step to implement the payment gateway.
Step 1. Create a new Flutter project
Step 2. Add the below dependencies in your app pubspec.yaml.
razorpay_flutter: ^1.3.5
http: ^1.0.0
Step 3. Edit your main.dart
Please replace the below code with the existing code.
import 'package:flutter/material.dart';
import 'MyHomePage.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
Step 4. Create a new file named MyHomePage.dart
Create a new file named MyHomePage.dart inside the lib folder.
Step 5. Import the required packages
Please import the below package inside the MyHomePage.dart file.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
import 'package:http/http.dart'as http;
Step 6. Create an instance of the Razorpay class
Razorpay _razorpay = Razorpay();
Step 7. Configure the payment options and other details
// Replace your apiKey & apiSecret;
String apiKey = 'YOUR_RAZORPAY_API_KEY';
String apiSecret = 'YOUR_RAZORPAY_API_SECRET';
Map<String, dynamic> paymentData = {
'amount': 1000, // amount in paise (e.g., 1000 paise = Rs. 10)
'currency': 'INR',
'receipt': 'order_receipt',
'payment_capture': '1',
};
Step 8. Create a function to make the API request and initiate the payment
Future<void> initiatePayment() async {
String apiUrl = 'https://api.razorpay.com/v1/orders';
// Make the API request to create an order
http.Response response = await http.post(
Uri.parse(apiUrl),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ${base64Encode(utf8.encode('$apiKey:$apiSecret'))}',
},
body: jsonEncode(paymentData),
);
if (response.statusCode == 200) {
// Parse the response to get the order ID
var responseData = jsonDecode(response.body);
String orderId = responseData['id'];
// Set up the payment options
var options = {
'key': apiKey,
'amount': paymentData['amount'],
'name': 'Sweet Corner',
'order_id': orderId,
'prefill': {'contact': '1234567890', 'email': '[email protected]'},
'external': {
'wallets': ['paytm'] // optional, for adding support for wallets
}
};
// Open the Razorpay payment form
_razorpay.open(options);
} else {
// Handle error response
debugPrint('Error creating order: ${response.body}');
}
}
Step 9. Set up callback handlers for success, failure, and cancellation events
void _handlePaymentSuccess(PaymentSuccessResponse response) {
// Do something when payment succeeds
// Here we get razorpay_payment_id razorpay_order_id razorpay_signature
}
void _handlePaymentError(PaymentFailureResponse response) {
// Do something when payment fails
}
void _handleExternalWallet(ExternalWalletResponse response) {
// Do something when an external wallet is selected
}
Step 10. Register the callback handlers and dispose of the Razorpay instance
@override
void initState() {
_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
super.initState();
}
@override
void dispose() {
_razorpay.clear(); // Removes all listeners
super.dispose();
}
Step 11. Call the initiate payment method from the checkout button
ElevatedButton(
onPressed: () {
// checkout to payment
initiatePayment();
},
child: const Text("Checkout"),
),
Step 12. Check your minSdkVersion
Please check your minSdkVersion inside android/app/build.gradle file and make sure it will be above or equal to 19.
minSdkVersion 19
Full Code Snippet
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
import 'package:http/http.dart'as http;
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _razorpay = Razorpay();
String apiKey = 'rzp_test_R3dodAqKlWEH1f';
String apiSecret = 'lqwRZBuPsjQlKK82Fh2gWC30';
Map<String, dynamic> paymentData = {
'amount': 50000, // amount in paise (e.g., 1000 paise = Rs. 10)
'currency': 'INR',
'receipt': 'order_receipt',
'payment_capture': '1',
};
@override
void initState() {
_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
super.initState();
}
@override
void dispose() {
_razorpay.clear(); // Removes all listeners
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text('Payment Gateway Example',style: TextStyle(color: Colors.white),),
),
body: Card(
margin: const EdgeInsets.only(left: 10,right: 10,top: 10),
child: ListTile(
title: const Text("Special Chum Chum",style: TextStyle(color: Colors.green,fontWeight: FontWeight.bold,fontSize: 20),),
subtitle: const Text('Special Bengali Sweet'),
trailing: ElevatedButton(
onPressed: () {
// checkout to payment
initiatePayment();
},
child: const Text("Checkout"),
),
),
),
);
}
void _handlePaymentSuccess(PaymentSuccessResponse response) {
// Do something when payment succeeds
// Here we get razorpay_payment_id razorpay_order_id razorpay_signature
}
void _handlePaymentError(PaymentFailureResponse response) {
// Do something when payment fails
}
void _handleExternalWallet(ExternalWalletResponse response) {
// Do something when an external wallet is selected
}
Future<void> initiatePayment() async {
String apiUrl = 'https://api.razorpay.com/v1/orders';
// Make the API request to create an order
http.Response response = await http.post(
Uri.parse(apiUrl),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ${base64Encode(utf8.encode('$apiKey:$apiSecret'))}',
},
body: jsonEncode(paymentData),
);
if (response.statusCode == 200) {
// Parse the response to get the order ID
var responseData = jsonDecode(response.body);
String orderId = responseData['id'];
// Set up the payment options
var options = {
'key': apiKey,
'amount': paymentData['amount'],
'name': 'Sweet Corner',
'order_id': orderId,
'prefill': {'contact': '1234567890', 'email': '[email protected]'},
'external': {
'wallets': ['paytm'] // optional, for adding support for wallets
}
};
// Open the Razorpay payment form
_razorpay.open(options);
} else {
// Handle error response
debugPrint('Error creating order: ${response.body}');
}
}
}
Step 13. Press the play button or shift+F10 and launch your app
Output
Test Cases
Please check out the official document for test cases - https://razorpay.com/docs/payments/payment-gateway/flutter-integration/standard/test-integration/
Conclusion
In this article, we have seen how to integrate the Razorpay payment gateway in Flutter. Thanks for reading, and I hope you like it. If you have any suggestions or queries on this article, please share your thoughts.
Are you an Android developer and want to integrate the Razorpay payment gateway in Android? Please check out the below article.
Happy learning, friends!