Flutter Stripe Integration Super Easy

Affan Minhas
Blocship
Published in
4 min readMar 31, 2023

Flutter is an open-source mobile application development framework that enables developers to build high-performance, visually stunning mobile apps for Android and iOS platforms. Stripe, on the other hand, is an online payment processing platform that helps businesses accept online payments securely and easily. In this article, we will go through the process of integrating Stripe into Flutter.

Prerequisites

Before we dive into the integration process, there are a few prerequisites you need to fulfill:

  • A Flutter development environment set up on your system
  • A Stripe account with API keys
  • Basic knowledge of Flutter and Dart programming language

Step 1: Add Dependencies

The first step is to add the Stripe and http packages as dependencies in your Flutter app. You can do this by adding the following lines in the pubspec.yaml file:

dependencies:
flutter_stripe: ^9.0.0+1
http: ^0.12.2

After adding the dependencies, run the command “flutter pub get” to download and install them.

Step 2: Configure Stripe API Keys

To configure the Stripe API keys, navigate to your Stripe dashboard and locate the API keys section. You will need both the public and secret keys for the integration. Copy the keys and save them somewhere safe as you will need them later in the integration process.

If you don’t have a stripe account so don’t worry it’s free you can easily signup.

OR I am sharing with you the test API Keys which you can use for practice. If you are integrating stripe for your client then he will provide you with both publishable and secret keys for this process.

Stripe Test Credentials:

Publishable Key: pk_test_TYooMQauvdEDq54NiTphI7jx

Secret Key: sk_test_4eC39HqLyjWDarjtT1zdp7dc

Step 3: Set Publishable Key

First, you have to set the publishable key that is used to identify the account on the Stripe platform. You can set it in your main.dart file by passing a publishable key to it as given below.

void main() async {
WidgetsFlutterBinding.ensureInitialized();
Stripe.publishableKey = 'pk_test_TYooMQauvdEDq54NiTphI7jx';
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(MyAppView());
}

Step 4: Make a Stripe Payment

Let me explain the code in a piecewise manner 😃 First, create a variable with the data type of Map like this outside the function anywhere;

Map<String, dynamic>? paymentIntent;
 paymentIntent = await createPaymentIntent(double.parse(amount).toInt().toString(), 'AED');

In this what I am doing like just creating a payment intent by calling the method createPaymentIntent which takes two positional parameters one is the amount you want to check out and the second one is the currency. This createPaymentIntent is not a built-in function I am creating it below as;

This is the post request which takes the header with your secret key and body as Map with your amount and currency. If you see in the body we are calculating the amount by calling the function,

calculateAmount(String amount) {
final calculatedAmount = (int.parse(amount)) * 100;
return calculatedAmount.toString();
}

We are doing this because stripe accepts payment in cents.

After decoding you will have a response that will return to the payment Intent where it was called. Now we will create a stripe instance for further processing as;

await Stripe.instance
.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntent!['client_secret'],
// applePay: const PaymentSheetApplePay(merchantCountryCode: '+92',),
// googlePay: const PaymentSheetGooglePay(testEnv: true, currencyCode: "US", merchantCountryCode: "+92"),
merchantDisplayName: 'Customer Name',
),
)
.then((value) {});

This piece of code is just creating a stripe instance by passing you the payment intent that you have just created.

So the complete function will look like this;

Future<void> makePayment(BuildContext context, String amount) async {
try {
paymentIntent = await createPaymentIntent(double.parse(amount).toInt().toString(), 'AED');
//Payment Sheet
await Stripe.instance
.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntent!['client_secret'],
// applePay: const PaymentSheetApplePay(merchantCountryCode: '+92',),
// googlePay: const PaymentSheetGooglePay(testEnv: true, currencyCode: "US", merchantCountryCode: "+92"),
merchantDisplayName: 'Mouaz User',
),
)
.then((value) {});

///now finally display payment sheeet
displayPaymentSheet(context, amount);
} catch (e, s) {
log('exception:$e$s');
}
}

Then it calls the displayPaymentSheet(context, amount); which will present the stripe payment process and then show success if payment is completed.

displayPaymentSheet(BuildContext context, String amount) async {
try {
await Stripe.instance.presentPaymentSheet().then((value) async {
showCustomSnackBar(title: 'Success', message: 'Payment Successful');
paymentIntent = null;
}).onError((error, stackTrace) {
log('Error is:--->$error $stackTrace');
});
} on StripeException catch (e) {
log('Error is:---> $e');
} catch (e) {
log('$e');
}
}

Step 5: Call Stripe Payment Method

Now you just have to design any button and on Press of it just call the function as ;

makePayment(context, '125');

Boom! 🤩 You have successfully integrated stripe in your flutter app. You can see how easy it is.

I am sharing with you the file having all functions written on it so you can easily understand it. If you have any difficulty you can reach out.

Thank You!

Have a nice learning ☺️

https://www.linkedin.com/in/affan-minhas-36858a213/

--

--