So, you're building a fantastic Flutter app and need to integrate a secure and reliable payment gateway? Look no further! Razorpay is a popular choice for Indian businesses, offering a seamless payment experience. This guide will walk you through the process of integrating Razorpay with your Flutter application, step-by-step, using Dart. We'll cover everything from setting up your Razorpay account to handling successful and failed transactions.
1. Setting Up Your Razorpay Account and Generating API Keys
Before diving into the code, you'll need a Razorpay account. Head over to the Razorpay website and sign up for a free account. Once you're logged in, switch to "Live Mode" or "Test Mode" (for development). In the dashboard, navigate to "Settings" -> "API Keys" and generate your API Key ID and API Key Secret. Important: Keep these keys secure and don't commit them directly to your codebase! Use environment variables or secure storage.
Important Note: For testing purposes, use Test Mode API Keys. Live Mode requires you to complete the KYC process.
2. Adding the Razorpay Flutter Package
Next, we'll add the official Razorpay Flutter package to your Flutter project. Open your pubspec.yaml file and add the following dependency:
dependencies:
razorpay_flutter: ^1.3.5 # Check for the latest version on pub.dev
Save the file, and then run flutter pub get in your terminal to download and install the package.
3. Implementing the Payment Flow in Flutter
Now, let's write the Dart code to initiate the Razorpay payment. Here's a basic example:
import 'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
class PaymentScreen extends StatefulWidget {
@override
_PaymentScreenState createState() => _PaymentScreenState();
}
class _PaymentScreenState extends State<PaymentScreen> {
Razorpay _razorpay = Razorpay();
@override
void initState() {
super.initState();
_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
}
void _openCheckout() {
var options = {
'key': 'YOUR_RAZORPAY_KEY_ID', // Replace with your Key ID
'amount': 10000, // Amount in paise (e.g., 10000 for ₹100)
'name': 'My Awesome App',
'description': 'Payment for your awesome product',
'prefill': {
'name': 'John Doe',
'email': 'john.doe@example.com',
'contact': '9876543210'
},
'theme': {
'color': '#F37254'
}
};
try {
_razorpay.open(options);
} catch (e) {
debugPrint(e.toString());
}
}
void _handlePaymentSuccess(PaymentSuccessResponse response) {
// Do something when payment succeeds
print("Payment Successful: ${response.paymentId}");
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Payment Successful!"),
content: new Text("Payment ID: ${response.paymentId}"),
actions: [
new ElevatedButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void _handlePaymentError(PaymentFailureResponse response) {
// Do something when payment fails
print("Payment Failed: ${response.code} - ${response.message}");
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text("Payment Failed!"),
content: new Text("Error Code: ${response.code}\nMessage: ${response.message}"),
actions: [
new ElevatedButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void _handleExternalWallet(ExternalWalletResponse response) {
// Do something when an external wallet is selected
print("External Wallet Selected: ${response.walletName}");
}
@override
void dispose() {
super.dispose();
_razorpay.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Razorpay Integration'),
),
body: Center(
child: ElevatedButton(
onPressed: _openCheckout,
child: Text('Pay Now'),
),
),
);
}
}
Explanation:
- Replace
YOUR_RAZORPAY_KEY_IDwith your actual Razorpay Key ID. - The
amountis specified in paise (100 paise = ₹1). So,10000represents ₹100. - The
optionsmap contains various payment parameters like amount, name, description, prefill information, and theme. - The
_razorpay.open(options)method initiates the Razorpay checkout process. - Event listeners are attached to handle payment success (
_handlePaymentSuccess), failure (_handlePaymentError), and external wallet selection (_handleExternalWallet). - Always dispose of the `_razorpay` instance in the `dispose()` method to prevent memory leaks.
4. Handling Payment Success and Failure
The _handlePaymentSuccess and _handlePaymentError methods are crucial for handling the payment outcome. In the success handler, you can update your app's state, provide confirmation to the user, and process the order. In the failure handler, you should display an error message to the user and allow them to retry the payment.
Important: Always verify the payment status with Razorpay's servers using their APIs to prevent fraud. Don't rely solely on the client-side response.
Conclusion
Integrating Razorpay with your Flutter app allows you to accept payments securely and efficiently. Remember to keep your API keys safe, handle payment success and failure gracefully, and always verify payment status on the server-side. This guide provides a solid foundation for building a robust payment solution in your Flutter application. Good luck!
Automated post via TechCognita Automation Framework
Comments
Post a Comment