How to Integrate Razorpay Payment Gateway in Flutter?
Last Updated :
24 Apr, 2025
Razorpay helps process online payments for online as well as offline businesses. Razor pay allows you to accept credit cards, debit cards, net banking, wallet, and UPI payments with the Mobile App integration. It uses a seamless integration, allowing the customer to pay on your app/website without being redirected away. In this article, we will take a look at the implementation of a payment gateway in our Flutter app.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Add Razorpay in pubspec.yaml file
Add Razorpay package to your flutter projects
Dart
// add package
razorpay_flutter: ^1.3.4
Version may vary depending upon the time you read this article.
Â
Step 3: Get API_key and API_secret for Razorpay
Browser the Razorpay site in Google or you can click on the link here. After clicking on this link you simply have to signup with your email and password and add some basic information such as your phone number.
Â
Note: Here we are creating a testing credential for using Razor Pay.
Inside the setting screen, click on Create a new key option your key will be generated. We will be using key ID in our application to test Razor pay. The key-id will start with rzp_test.
Â
To store Razor pay key and secret in the flutter app (Without sharing it on github,gitlabs). You can refer to this article: How to Add .env File in Flutter
Step 4: Create Razorpay Instance
To access all functions, and variables of Razorpay you have to create the instance for that.
Dart
// Instance of razor pay
final Razorpay _razorpay = Razorpay();
Â
Step 5: Attach Event listeners
To perform different functions on every event that happens in Razorpay you have to handle different scenarios.
1. Create functions to handle different events
Dart
void _handlePaymentSuccess(PaymentSuccessResponse response) {
// Do something when payment succeeds
}
void _handlePaymentError(PaymentFailureResponse response) {
// Do something when payment fails
}
void _handleExternalWallet(ExternalWalletResponse response) {
// Do something when an external wallet is selected
}
Â
2. Attach these functions to event listeners
In this, you have to attach the previous  function to events listeners by this
Dart
initiateRazorPay() {
// To handle different event with previous functions
_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
}
Â
Step 6: Create order in Razorpay
Either you can create an order id from the server using the Razorpay api secret and api key or you can create an order id in the app itself. This postman request you will be required to create an order id
curl -X POST https://api.razorpay.com/v1/orders
-u [YOUR_KEY_ID]:[YOUR_KEY_SECRET]
-H 'content-type:application/json'
-d '{
"amount": 100,
"currency": "INR",
"receipt": "rcptid_11" //receipt id you want to give
}'
To create order Id in the app itself:
Dart
import 'dart:convert';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:http/http.dart' as http;
class ApiServices {
final razorPayKey = dotenv.get("RAZOR_KEY");
final razorPaySecret = dotenv.get("RAZOR_SECRET");
razorPayApi(num amount, String receiptId) async {
var auth =
'Basic ' + base64Encode(utf8.encode('$razorPayKey:$razorPaySecret'));
var headers = {'content-type': 'application/json', 'Authorization': auth};
var request =
http.Request('POST', Uri.parse('https://api.razorpay.com/v1/orders'));
request.body = json.encode({
// Amount in smallest unit
// like in paise for INR
"amount": amount * 100,
// Currency
"currency": "INR",
// Receipt Id
"receipt": receiptId
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
print(response.statusCode);
if (response.statusCode == 200) {
return {
"status": "success",
"body": jsonDecode(await response.stream.bytesToString())
};
} else {
return {"status": "fail", "message": (response.reasonPhrase)};
}
}
}
Sample Response for this APIÂ
{
"id": "order_DBJOWzybf0sJbb",
"entity": "order",
"amount": 100,
"amount_paid": 0,
"amount_due": 100,
"currency": "INR",
"receipt": "rcptid_11",
"status": "created",
"attempts": 0,
"notes": [],
"created_at": 1566986570
}
Create order in Your flutter app:
How to call Create an order
Note: You can put your amount in place of 100. You have to add the amount in integer value only and razor pay takes the amount in a smaller unit for example in India it takes the amount in paise. For the USA it takes in cents.
Store this ID in a variable. It will be requiring in when you open checkout sessions.
Step 7: Add checkout sessions
Create order id by calling create order function and prepare the parameter to be sent to the Razorpay checkout pageÂ
Dart
// to get orderid by creating new order everytime
// you try to open razorpay checkout page
createOrder(amount: amount).then((orderId) {
print(orderId);
if (orderId.toString().isNotEmpty) {
var options = {
// Razorpay API Key
'key': razorPayKey,
// in the smallest
// currency sub-unit.
'amount': amount,
'name': 'Company Name.',
// Generate order_id
// using Orders API
'order_id': orderId,
// Order Description to be
// shown in razor pay page
'description':
'Description for order',
// in seconds
'timeout': 60,
'prefill': {
'contact': '9123456789',
'email': '[email protected]'
} // contact number and email id of user
};
} else {}
});
Step 8: Open Checkout Page
Now just open the checkout page and pay with different payment methods
Dart
Â
Step 9: Store fields in the server
For a better user experience and data security kept these 3 fields in your database. This will be returned in the successful event function if the transaction is successfully made.
{
"razorpay_payment_id": "pay_29QQoUBi66xm2f",
"razorpay_order_id": "order_9A33XWu170gUtm",
"razorpay_signature": "9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d"
}
Step 10: Verify signature and payment
This step is necessary to verify the validity of the information returned to the Checkout form for successful payments.
generated_signature = hmac_sha256(order_id + "|" + razorpay_payment_id, secret);
if (generated_signature == razorpay_signature) {
payment is successful
}
Output:
Github Source Code: Click here
Similar Reads
How to Integrate Razorpay Payment Gateway in Android?
Many apps nowadays require to have a payment gateway inside their application so that users can do any transactions inside their apps to purchase any product or any service. Many apps use the payment gateway features but the integration of this payment gateway is a difficult task in Android applicat
5 min read
Flutter - Integrate Stripe Payment Gateway
Stripe is a platform that allows businesses to handle online transactions and add payment gateway in your applications or websites all over the world with different currencies.It is secure and easy to use.It supports 135+ countries and can handle foreign currency automatically.It gives proper report
6 min read
Flutter - Cashfree Payment Gateway Integration
The Cashfree Flutter SDK allows you to integrate Cashfree Payment Gateway into your application and start collecting payments from your customers. It is designed to minimise the complexity of handling and integrating payments in your Flutter project. So in this article, we are going to integrate Cas
9 min read
Flutter - How to Integrate Mapbox
Maps have become an aspect of our routines. Whether you're exploring a city looking for a coffee shop or keeping tabs on delivery maps is incredibly valuable. When it comes to creating apps incorporating maps not only improves the user experience but is also frequently necessary, for applications th
7 min read
How to Integrate Google Maps in Flutter Applications?
We all have seen that Google Maps is used by many applications such as Ola, Uber, Swiggy, and others. We must set up an API project with the Google Maps Platform in order to integrate Google Maps into our Flutter application. In this article, we will look at How to Integrate Google Maps in Flutter A
4 min read
How to Generate SHA-1 Key in Flutter?
SHA-1(Secure Hash Algorithm) is the unique identity of your Application. In Flutter, you can use these keys for various purposes such as adding Firebase to your app, Google Maps API integration, and more. For example, to add Firebase to your app, you need to provide the SHA-1 and SHA-256 keys to the
2 min read
How to Import intl Library in Flutter?
Flutter supports using shared packages contributed by other developers to the Flutter and Dart ecosystems. This allows the developers to quickly build an app without having to develop everything from scratch. One such very helpful and Flutter Favourite package is the intl package published by the da
2 min read
How to Install Shared Preferences in Flutter?
Shared preferences in flutter applications are used to store data in Local Storage. Shared Preferences store the data in a key-value pair. and we can also get data in a key-value pair using inbuilt functions. We can save large data in local storage or our Phone storage with the help of SQLite databa
2 min read
How to Install HTTP Package in Flutter?
Flutter is Googleâs Mobile SDK to build native iOS and Android apps from a single codebase. When building applications with Flutter everything towards Widgets â the blocks with which the flutter apps are built. The User Interface of the app is composed of many simple widgets, each of them handling o
2 min read
How to Add Route Polylines to Google Maps in Flutter?
Google Maps is used in many Android applications. We can use Polylines to represent routes for various destinations on Google Maps. So in this article, we are going to add Route Polylines to Google Maps in Flutter. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo set up Fl
4 min read