logo

Education

Bridging Payments in Flutter with Stripe: An Essential Guide to Flutter Stripe Package

Authore Name
Nidhi Sorathiya

Software Development Executive - II

Last updated on Nov 8, 2023

Importance of Online Payments in Digital Applications

In today's digital world, online payments are integral to catering to a global audience. It's mandatory for any modern mobile application to provide a robust and secure payment integration. As Flutter developers seek easy-to-use but powerful solutions for this, Stripe takes center stage.

Stripe, a leading online payment processing platform, empowers businesses to manage transactions smoothly and securely. Integrating Stripe with Flutter applications enhances their overall capability, allowing them to process online payments effectively. This blog will guide Flutter devs on this integration using the flutter_stripe package.

Let's start by introducing our tools of trade: Stripe and Flutter.

What is Stripe?

Stripe is a comprehensive payment gateway with APIs that allow businesses to collect payment details and carry out transactions securely. Stripe can process all major debit and credit cards and supports other payment methods such as Apple Pay, Google Pay, and many more.

The Stripe API is robust, developer-friendly, and easy to work with, making it no surprise that Stripe Flutter integrations are common when building mobile applications.

About Flutter

Flutter is Google's UI toolkit for crafting beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. This open-source framework is easy to use and powerful, making it an ideal choice for developers. Integrating payment gateways like Stripe using the flutter_stripe package fuels the growth of the business and enhances their Flutter applications.

Setting up a Development Environment

Before we begin our journey with Flutter Stripe, we need to ensure our development environment is set up correctly. First, let's take care of Flutter.

If you haven't installed Flutter on your local system, follow the official Flutter installation guide for detailed instructions. Remember, to test your Stripe integration in your Flutter application, you will need a physical mobile device or an emulator for iOS or Android.

Now, let's set up a Stripe account.

Creating a Stripe Account

  1. Visit the Stripe website and sign up for an account if you haven't already done so.
  2. Navigate to the Stripe dashboard and retrieve your API keys. Stripe provides two keys: a publishable key (pk_test) and a secret key (sk_test). These keys identify your Stripe account when using the Stripe API.

Remember, for security reasons, never expose the secret key and keep it confidential.

Next, let's add the package to our Flutter application.

Installing the Flutter Stripe Package

The flutter_stripe package is a wrapper around the Stripe API, simplifying the process of integrating Stripe into your Flutter application. It's designed with simplicity and ease of use, letting you focus on creating delightful payment experiences for your users.

Add the flutter_stripe package to your Flutter project using the following command in your terminal:

1flutter pub add flutter_stripe

This command adds the package to your pubspec.yaml file and runs the Flutter Pub get command that fetches all the packages your project depends on. If your code editor supports it, this command may run implicitly.

Now, import the flutter_stripe package into your dart file where you plan to implement the Stripe functionalities:

1import 'package:flutter_stripe/flutter_stripe.dart';

With the flutter_stripe package installed, you're ready to integrate Stripe into your Flutter application.

Initialization of the Flutter Stripe Package

The next critical step for integrating Stripe into your Flutter application is initializing the flutter_stripe package. Initially, we initialize Stripe with our publishable key from our Stripe Dashboard. This initialization is necessary for communication between the Flutter Stripe API and your Stripe account. It sets up the base for creating a payment sheet and handling all stripe-related actions.

Include the initialization of Stripe in the void main() function of your Dart file or your Flutter app's initialization state. However, beware to initialize it only a few times throughout your app. Here's a code snippet to demonstrate how you might go about this.

1import 'package:flutter/material.dart'; 2import 'package:flutter_stripe/flutter_stripe.dart'; 3 4void main() { 5 WidgetsFlutterBinding.ensureInitialized(); 6 Stripe.publishableKey = "your-publishable-key"; 7 Stripe.merchantIdentifier = "merchant.identifier"; 8 9 runApp(MyApp()); 10} 11 12class MyApp extends StatelessWidget { 13 // This widget is the root of your application. 14 @override 15 Widget build(BuildContext context) { 16 return MaterialApp( 17 title: 'Flutter Stripe Demo', 18 theme: ThemeData( 19 primarySwatch: Colors.blue, 20 visualDensity: VisualDensity.adaptivePlatformDensity, 21 ), 22 home: MyHomePage(), 23 ); 24 } 25}

Once you've initialized Stripe in your Flutter app, it's ready for your users to enter and process payment details.

Establishing a Payment Intent

Understanding Payment Intent

When developing a vast Flutter application with various payment methods, including cards and digital wallets like Google Pay and Apple Pay, the concept of a Payment Intent becomes crucial. Payment Intent in Stripe API represents a payment's lifecycle and involves several stages, from initial creation and handling of payment details to final confirmation.

Setting up the Payment Intent

To set up the Payment Intent, create a Payment Intent ID from your server side, typically when your customer begins a checkout. This Payment Intent ID is then passed to your Flutter Stripe SDK from the client side to confirm and handle the payment embedded in the Payment Intent.

While we won't delve into the server-side setup in this blog, you can explore the Stripe documentation to understand how to create a Payment Intent on your server and pass the Payment Intent client secret to your client application.

Next, we will capture the payment details that should be tied to the payment intent we just set up.

Attaching Payment Details

Now that our Flutter application has created a payment intent, the next step in processing payments is collecting and attaching the user's payment details to this intent.

Stripe's flutter_stripe package provides an out-of-the-box UI to collect these card details securely. Remember, we must never collect sensitive data like a user's card details to stay PCI compliant. Stripe takes care of this for us.

This package offers three main ways to collect card details:

  1. Payment Sheet: It is the recommended way to handle payments as it offers localization, animations, and error handling out of the box.
  2. CardField: It is a single-line card field that offers more flexibility but has less built-in functionality.
  3. Card Form: This is similar to the CardField, but the entry fields are spread across multiple lines.

Once the user provides their card details using either of the methods above, you can save this as a payment method for further use.

In the next sections, we will explore integrating Google Pay with your Flutter application using flutter_stripe.

Integrating Google Pay with Stripe

Expanding payment options to include digital wallets like Google Pay not only provides a better user experience but also boosts checkout conversion. Thanks to the flutter_stripe package, integrating Google Pay with the Flutter Stripe API is streamlined.

The flutter_stripe package leverages the Pay plugin developed by Google to facilitate Google Pay integration. To implement this, provide your Stripe publishable key to the payment profile.

1import 'package:flutter_stripe/flutter_stripe.dart'; 2import 'package:stripe_platform_interface/stripe_platform_interface.dart'; 3 4Future<void> initGooglePay() async { 5 await Stripe.instance.applySettings( 6 PaymentSheet.BillingAddressConfig( 7 googlePay: true, 8 applePay: false, 9 style: GooglePayButtonStyle.black, 10 type: GooglePayButtonType.pay, 11 ), 12 GooglePayInitParams( 13 merchantName: 'Example Merchant', 14 countryCode: 'US', 15 ), 16 ); 17}

Once initialized, Google Pay can be used as a payment method:

1Future<void> payWithGooglePay() async { 2 final PaymentSheetResult result = await Stripe.instance.presentGooglePay( 3 SetupGooglePayParameters( 4 currencyCode: 'usd', 5 countryCode: 'US', 6 testEnv: true, 7 ), 8 ); 9 10 if(result.isSuccessful) { 11 // Handle success scenario. 12 } else { 13 // Handle error scenario. 14 } 15}

Integrating Google Pay provides users a frictionless and secure payment process, increasing conversions and positively impacting your bottom line.

Implementing the Stripe Checkout in the Flutter App

Let's introduce the Stripe Checkout in your Flutter application now. Stripe Checkout is a pre-built, hosted payment page optimized for conversion—perfect for businesses looking to start accepting payments quickly. It works seamlessly with mobile and is designed to feel intuitive to your users. With Stripe Checkout, customers can pay with their preferred payment methods, including credit/debit cards and digital wallets such as Apple Pay and Google Pay.

To implement the Stripe Checkout, first initialize the PaymentSheet parameters, which include the Stripe API keys, payment intent client secret, and additional details such as customer information. Then, present the payment sheet to users to securely collect their payment information.

Here's a simple code snippet which demonstrates how to create and present the Payment Sheet:

1import 'package:flutter_stripe/flutter_stripe.dart'; 2 3// First you need to setup payment sheet 4await Stripe.instance.initPaymentSheet( 5 paymentSheetParameters: SetupPaymentSheetParameters( 6 paymentIntentClientSecret: 'paymentIntentClientSecret', 7 applePay: true, 8 googlePay: true, 9 style: ThemeMode.dark, 10 merchantCountryCode: 'US', 11 merchantDisplayName: 'Your Company', 12 ), 13); 14 15// Then, you can display the payment sheet. 16final paymentResult = await Stripe.instance.presentPaymentSheet( 17 parameters: PresentPaymentSheetParameters( 18 // Returns to the initial PaymentSheet presentation. 19 clientSecret: paymentIntentClientSecret, 20 confirmPayment: true, 21)); 22if (paymentResult.isSuccess) { 23 // Handle the successful payment. 24}

With Stripe Checkout, you can now easily manage accepting payments with different payment methods. It offers a delightful payment experience for end users and can greatly simplify code on the Flutter application side.

Performing Transactions

Once your Flutter Stripe integration has the necessary payment details, you can perform transactions. A transaction is completed when the client application sends a request to the server, and the server asks Stripe to charge the customer's chosen payment method.

While charging a payment method is usually done on the server side, the Flutter Stripe SDK provides ways to handle actions that need to be done from the client side, like confirming the PaymentIntent:

1import 'package:flutter_stripe/flutter_stripe.dart'; 2 3final paymentIntent = await Stripe.instance.confirmPayment( 4 'PaymentIntentClientSecret', 5 PaymentMethodParams.card( 6 // We don't need to collect these details in our app, as we are using the pre-built payment sheet. 7 // More details can be captured if the custom flow is implemented. 8 ), 9); 10if(paymentIntent.status == PaymentIntentsStatus.succeeded) { 11 // payment was successful. Update your UI accordingly. 12} else { 13 // Payment not successful. Show an error message. 14}

After charging the payment method and confirming the PaymentIntent, Stripe will execute the transaction, and the payment will be finalized.

Handling Errors

In any application, handling errors effectively is key to providing a good user experience. Errors may occur while performing transactions, setting up payment sheets, or even initializing Stripe.

When conducting a transaction, errors can be related to the client device, the network, or the server-side setup. As such, any function that performs a transaction should be appropriately surrounded by try-catch blocks to handle potential exceptions:

1import 'package:flutter_stripe/flutter_stripe.dart'; 2 3try { 4 final paymentIntent = await Stripe.instance.confirmPayment( 5 'PaymentIntentClientSecret', 6 PaymentMethodParams.card( 7 ), 8 ); 9 if(paymentIntent.status == PaymentIntentsStatus.succeeded) { 10 // Payment was successful, update your UI accordingly. 11 } else { 12 // Payment not successful. Show an error message. 13 } 14} catch (e) { 15 // Deal with the caught error. 16}

By handling errors correctly, we can provide more helpful feedback to users and maintain their faith in our application.

Testing the Flutter Stripe Payment Functionality

Before we deploy our Flutter application, it's essential to test our Stripe integration thoroughly. Stripe provides various testing tools that help troubleshoot and verify our integration.

Stripe's test mode helps us simulate transactions and check the integration without accurate charges. We can use the test API keys to create any API request without affecting live data or interacting with the banking networks.

Here's how we can switch to test mode in our flutter_stripe environment:

1import 'package:flutter_stripe/flutter_stripe.dart'; 2Stripe.publishableKey = "your-test-publishable-key"; 3... 4// While creating the payment sheet 5await Stripe.instance.initPaymentSheet( 6 paymentSheetParameters: SetupPaymentSheetParameters( 7 paymentIntentClientSecret: 'test-paymentIntentClientSecret', 8 testEnv: true, 9 ... 10 ) 11);

You can now perform test transactions on your application, debug issues, and ensure your setup is as expected. Once you are happy with your testing, switch back to your live API keys for deploying your app.

With that, we've covered the essentials of integrating Stripe into a Flutter app using the flutter_stripe package, from setting up to making transactions and testing them. While it seems like a lot, we've barely scratched the surface of the possibilities and the potential of what you can achieve.

Conclusion

In the realm of online transactions, Stripe stands out for its developer-friendly services and extensive capabilities. Introducing the flutter_stripe package has bridged the gap between Flutter and Stripe, embodying the ease of integrating complex payment setups into Flutter applications.

Through this guide, we delved into initializing Stripe in your Flutter apps, setting up a Payment Intent, gathering and attaching Payment Details, integrating Google Pay as an additional payment medium, and handling transactions and potential errors. Beyond these, we also highlighted the importance of testing your Stripe integration before going live.

Mastering Stripe's detailed setup may appear daunting initially, but the fruitful results in your Flutter applications will certainly make the effort worthwhile.

References

To further familiarize yourself with Stripe and its Flutter integration, here are some invaluable sources:

  1. Stripe API Reference
  2. Flutter Stripe Package
  3. Stripe's Testing Guide
  4. Flutter Installation

We hope you found this guide insightful and are now excited to implement what you have learned. Keep Fluttering!

Thank you for reading!

Short on time? Speed things up with DhiWise!!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Read More