Flutter - Cashfree Payment Gateway Integration
Last Updated :
24 Apr, 2025
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 Cashfree Payment Gateway with the Flutter application.
Step By Step Implementation
Step 1: Create a New Flutter Project in IDE
Create a simple flutter project either using Android Studio or by following the command
Dart
Step 2: Add the flutter_cashfree_pg_sdk package
Add the following package to your pubspec.yaml file
Dart
dependencies:
flutter_cashfree_pg_sdk: ^2.0.25+28
The version may get change depending on your usage. We have preferred this package because it is developed by cashfree itself and it is maintained project
Important Tips: Always Prefer to use package that are developed by some big companies. Use that is maintained regularly by publisher.
Step 3: Create the cashfree account and get the API key and API secret
Cretae cashfree account by going on this website. And get the API key and API secret from here. Go to developers which you can found on top of the cashfree dashboard.

In payment gateway option there will be API keys option you have to click that.

You can view API keys and update it .env file in your flutter project or save for serverside api calling.
Step 4: Now Create Cashfreepayment instance
We will create a simple cashfree payment instance like below to do all the activity during cashfree and bool variable for checking payment status.
Dart
// Cashfree Payment Instance
CFPaymentGatewayService cfPaymentGatewayService = CFPaymentGatewayService();
Step 5: Attach Event listeners
In the init function we will attach 2 events one will be call when payment is successfully done by user and another when some error happens. These are 2 function
1. Verifypayment
This will trigger when paymet is successfully done
Dart
void verifyPayment(String orderId) {
// Here we will only print the statement
// to check payment is done or not
isSuccess = true;
setState(() {});
print("Verify Payment $orderId");
}
This will contain order id which you may need to update in your database or anywhere as per your requirement
2. OnError
This will trigger when some error happens
Dart
void onError(CFErrorResponse errorResponse, String orderId) {
// printing the error message so that we can
// show it to user or checkourselves for testing
isSuccess = false;
setState(() {});
print(errorResponse.getMessage());
print("Error while making payment");
}
This will contain parameters for error response and ordered. We will attach this callback in cashfreeinstance in init state like this
Dart
@override
void initState() {
super.initState();
// Attach events when payment is success and when error occured
cfPaymentGatewayService.setCallback(verifyPayment, onError);
}
Step 6: We will create sessionid which will require in next step 6
In this we will create session id by passing some data into it which will require in next step. Generally this session id is create from server
curl --location 'https://sandbox.cashfree.com/pg/orders' \
--header 'Content-Type: application/json' \
--header 'x-client-id: CLIENT ID' \
--header 'x-client-secret: CLIENT SECRET' \
--header 'x-api-version: 2022-09-01' \
--header 'x-request-id: developer name' \
--data-raw '{
"order_amount": 1.00,
"order_id": "order_id",
"order_currency": "INR",
"customer_details": {
"customer_id": "customer_id",
"customer_name": "customer_name",
"customer_email": "customer_email",
"customer_phone": "+customer_mobile"
},
"order_meta": {
"notify_url": "https://test.cashfree.com"
},
"order_note": "some order note here"}'
You can use below curl for postman if you want it to create from there. To store API key and API secret We have use .env concept. You may refer to this article How to Add .env File in Flutter. If now we will create from flutter only by giving a simple API call using http.
Sample
You need to add http package and add following code in it. In this function there is orderID will also be required which must be unique and not in use by any previous transactions or orders.
Note: In customer details customer email,contact ,id is compulsory.
Dart
createSessionID(String orderID) async {
var headers = {
'Content-Type': 'application/json',
'x-client-id': dotenv.env["API_CLIENT"] ?? "",
'x-client-secret': dotenv.env["API_SECRET"] ?? "",
'x-api-version': '2022-09-01',// This is latest version for API
'x-request-id': 'fluterwings'
};
print(headers);
var request =
http.Request('POST', Uri.parse('https://sandbox.cashfree.com/pg/orders'));
request.body = json.encode({
"order_amount": 1,// Order Amount in Rupees
"order_id": orderID, // OrderiD created by you it must be unique
"order_currency": "INR", // Currency of order like INR,USD
"customer_details": {
"customer_id": "customer_id", // Customer id
"customer_name": "customer_name",// Name of customer
"customer_email": "[email protected]",// Email id of customer
"customer_phone": "+917737366393" // Phone Number of customer
},
"order_meta": {"notify_url": "https://test.cashfree.com"},
"order_note": "some order note here" // If you want to store something extra
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// If All the details is correct it will return the
// response and you can get sessionid for checkout
return jsonDecode(await response.stream.bytesToString());
} else {
print(await response.stream.bytesToString());
print(response.reasonPhrase);
}
}
Step 7: We will launch the page for payment by adding this code
In previous step we have created session ID which we will be used now
1. Create session for particular session in flutter by setting basic things like environment,orderid,sessionid
Dart
Future<CFSession?> createSession() async {
try {
final mySessionIDData = await createSessionID(
orderId); //This will create session id from flutter itself
// Now we will se some parameter like orderID ,environment,payment sessionID
// after that we wil create the checkout session which
// will launch through which user can pay.
var session = CFSessionBuilder()
.setEnvironment(CFEnvironment.SANDBOX)
.setOrderId(mySessionIDData["order_id"])
.setPaymentSessionId(mySessionIDData["payment_session_id"])
.build();
return session;
} on CFException catch (e) {
print(e.message);
}
return null;
}
2. Now we will finally launch the checkout page
Dart
pay() async {
try {
var session = await createSession();
List<CFPaymentModes> components = <CFPaymentModes>[];
// If you want to set paument mode to be shown to customer
var paymentComponent =
CFPaymentComponentBuilder().setComponents(components).build();
// We will set theme of checkout session page like fonts, color
var theme = CFThemeBuilder()
.setNavigationBarBackgroundColorColor("#FF0000")
.setPrimaryFont("Menlo")
.setSecondaryFont("Futura")
.build();
// Create checkout with all the settings we have set earlier
var cfDropCheckoutPayment = CFDropCheckoutPaymentBuilder()
.setSession(session!)
.setPaymentComponent(paymentComponent)
.setTheme(theme)
.build();
// Launching the payment page
cfPaymentGatewayService.doPayment(cfDropCheckoutPayment);
} on CFException catch (e) {
print(e.message);
}
}
Now payment page will open and we or user have to do payment.
Step 8: Now will verify the payment and update in cashfree
If payment is done successful then we will verify the payment and update its status if need in cashfree or in our database. We will simply print the statement for now. If payment is rejected or got some error we can handle different scenarios.But for now I have added the simple statement and update one variable where we can get to know whether payment is successful or not.
Complete Source Code:
Dart
class CashFreePayment extends StatefulWidget {
const CashFreePayment({super.key});
@override
State<CashFreePayment> createState() => _CashFreePaymentState();
}
class _CashFreePaymentState extends State<CashFreePayment> {
CFPaymentGatewayService cfPaymentGatewayService =
CFPaymentGatewayService(); // Cashfree Payment Instance
bool? isSuccess;
@override
void initState() {
super.initState();
// Attach events when payment is success and when error occured
cfPaymentGatewayService.setCallback(verifyPayment, onError);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Cashfree Payment Flutter Template'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(onPressed: pay, child: const Text("Pay")),
Text(
"Payment Status $isSuccess",
style: const TextStyle(fontSize: 20),
)
],
),
),
);
} // When payment is done successfully
void verifyPayment(String orderId) {
// Here we will only print the statement
// to check payment is done or not
isSuccess = true;
setState(() {});
print("Verify Payment $orderId");
}
// If some error occur during payment this will trigger
void onError(CFErrorResponse errorResponse, String orderId) {
// printing the error message so that we can show
// it to user or checkourselves for testing
isSuccess = false;
setState(() {});
print(errorResponse.getMessage());
print("Error while making payment");
}
String orderId = "my_order_id1";
Future<CFSession?> createSession() async {
try {
final mySessionIDData = await createSessionID(
orderId); // This will create session id from flutter itself
// Now we will se some parameter like orderID ,environment,payment sessionID
// after that we wil create the checkout session
// which will launch through which user can pay.
var session = CFSessionBuilder()
.setEnvironment(CFEnvironment.SANDBOX)
.setOrderId(mySessionIDData["order_id"])
.setPaymentSessionId(mySessionIDData["payment_session_id"])
.build();
return session;
} on CFException catch (e) {
print(e.message);
}
return null;
}
pay() async {
try {
var session = await createSession();
List<CFPaymentModes> components = <CFPaymentModes>[];
// If you want to set paument mode to be shown to customer
var paymentComponent =
CFPaymentComponentBuilder().setComponents(components).build();
// We will set theme of checkout session page like fonts, color
var theme = CFThemeBuilder()
.setNavigationBarBackgroundColorColor("#FF0000")
.setPrimaryFont("Menlo")
.setSecondaryFont("Futura")
.build();
// Create checkout with all the settings we have set earlier
var cfDropCheckoutPayment = CFDropCheckoutPaymentBuilder()
.setSession(session!)
.setPaymentComponent(paymentComponent)
.setTheme(theme)
.build();
// Launching the payment page
cfPaymentGatewayService.doPayment(cfDropCheckoutPayment);
} on CFException catch (e) {
print(e.message);
}
}
// webCheckout() async {
// try {
// var session = await createSession();
// var cfWebCheckout =
// CFWebCheckoutPaymentBuilder().setSession(session!).build();
// cfPaymentGatewayService.doPayment(cfWebCheckout);
// } on CFException catch (e) {
// print(e.message);
// }
// }
}
createSessionID(String orderID) async {
var headers = {
'Content-Type': 'application/json',
'x-client-id': dotenv.env["API_CLIENT"] ?? "",
'x-client-secret': dotenv.env["API_SECRET"] ?? "",
'x-api-version': '2022-09-01', // This is latest version for API
'x-request-id': 'fluterwings'
};
print(headers);
var request =
http.Request('POST', Uri.parse('https://sandbox.cashfree.com/pg/orders'));
request.body = json.encode({
"order_amount": 1, // Order Amount in Rupees
"order_id": orderID, // OrderiD created by you it must be unique
"order_currency": "INR", // Currency of order like INR,USD
"customer_details": {
"customer_id": "customer_id", // Customer id
"customer_name": "customer_name", // Name of customer
"customer_email": "[email protected]", // Email id of customer
"customer_phone": "+917737366393" // Phone Number of customer
},
"order_meta": {"notify_url": "https://test.cashfree.com"},
"order_note": "some order note here" // If you want to store something extra
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// If All the details is correct it will return the
// response and you can get sessionid for checkout
return jsonDecode(await response.stream.bytesToString());
} else {
print(await response.stream.bytesToString());
print(response.reasonPhrase);
}
}
Output:
1. When payment is successful
2. When payment is failed
Similar Reads
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
How to Integrate Razorpay Payment Gateway in Flutter?
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 b
5 min read
Flutter - Simple PDF Generating App
Flutter Community has created several packages to work with PDFs in our apps. In this article, we will be creating a simple PDF-generating app. This application will convert plain text to PDF. The packages that we are going to need are listed below with their uses:pdf: It is a PDF creation library f
9 min read
Flutter - Design Sample Registration Page
To prevent unauthorized access to personal information, it is a good practice to authenticate users before granting access to websites, mobile applications, and computer applications, then register and then login. In this article, we are going to explain how to build a Registration page user interfa
5 min read
Flutter - How to Get Instagram Username Data
Flutter is a cross-platform application development toolkit developed and maintained by Google. Flutter redefines cross-platform app development by combining great design with superb capabilities. Flutter was released to the public in 2017, and since then many large corporations have shifted towards
3 min read
Integrating Maps and Geolocation Services Flutter
In today's Android application, incorporating maps and geolocation services is essential. Whether it be finding the user's location, finding nearby travel places, or providing navigation, these features might really enhance the user experience and ease it down. Flutter, Google's UI toolkit for build
6 min read
Flutter - Realtime Database in Firebase
Firebase helps developers to build and run their apps successfully; its backend is developed by Google. Firebase is very easy to use for beginners; it provides many functionalities like Firebase Authentication, Cloud Firestore, Realtime Database, Firebase Storage, etc, which help to build and optimi
6 min read
Flutter - Create Instagram Login UI
Instagram is one of the most popular social media apps out there, with over 1 billion active users. As a developer, you may be interested in replicating its login UI using Flutter, one of the most popular cross-platform app development frameworks available. In this article, we will guide you through
5 min read
Flutter - Integrate Google Gemini API
Currently, Artificial Intelligence is blooming all around. You must have heard about the ChatGPT, Bard and now Google has come up with a very new Artificial intelligence Gemini which responds to users in a truly human-like way. You can connect Google Gemini with Flutter in a very simple and quick wa
6 min read
How to Add Firebase into Flutter in a New Way?
Recently Firebase give another option for adding Firebase to Flutter and It is only made for Flutter, As of now we add firebase using the android option for flutter but now we can add using the flutter option that is recently updated by Flutter. Here you can find how to add firebase as an Android in
2 min read