Emmanuel Etukudo I am a full-stack developer with more than five years of experience, with a preference for JavaScript, Node.js, Go, React, Redux, and MongoDB.

Exploring the Stripe Flutter SDK

5 min read 1638

Stripe Flutter SDK

Stripe is a popular payment processor that makes it easy for developers to integrate payment methods into mobile applications. With a heavy focus on UX and security, Stripe has shaken up the e-commerce industry with its popularity among both shoppers and developers.

Shortly after Stripe released an SDK for React Native, the Stripe Flutter SDK was introduced, building on the functionality of the Stripe API. In this tutorial, we’ll explore the  Stripe Flutter SDK by installing it and integrating it into an example application.

To follow along with this tutorial, you’ll need:

  • Flutter installed in your machine
  • Basic knowledge of Flutter
  • Familiarity with Dart
  • Xcode or Android Studio installed on your machine
  • iOS Simulator or an Android emulator for testing
  • A code editor, i.e., VS Code

Let’s get started!

The Stripe Flutter SDK

Let’s take a look at some of Stripe’s features that we’ll integrate into our Flutter app using the Stripe Flutter SDK.

Payment options

Stripe first gained notoriety for simplifying international transactions in applications by supporting multiple currencies. Currently, Stripe supports many types of electronic payments.

For example, you can easily integrate wallets like Apple Pay and Google Pay into your Flutter application. Similarly, Stripe supports most popular credit and debit cards, as well as buy now pay later methods like Klarna and Afterpay.

It is straightforward to transfer funds between bank accounts using methods like redirects and vouchers. Stripe offers a payout schedule that makes it easy for you to add your own bank account information and receive payments made through your mobile app.

Built-in UI

Stripe provides a native UI for securely accepting payments in both Android and iOS applications. Similarly, the SDK is shipped with a prebuilt UI for accepting payments in Google Pay and Apple Pay. However, you can easily build your own custom payment form in Stripe if you wish.

With Stripe’s built-in payment portal, you can set up either one-time purchases or fixed-price subscriptions.

We made a custom demo for .
No really. Click here to check it out.

Security

Stripe maintains its focus on security by sending sensitive payment information to its own server instead of the host’s backend server, simplifying the collection of data and remaining compliant with Payment Card Information (PCI) security standards.

Additionally, Stripe performs 3D Secure authentication to comply with Europe’s Strong Customer Authentication guidelines, protecting your users’ most important information.

Getting started with Stripe

If you don’t have a Stripe account, first, create a new one. You’ll need to obtain your personal access key from your account. Head to the Developer section and look under API Keys, as seen in the screenshot below:

Set Up New Stripe Application

Building a Flutter Stripe app

With the personal access keys in place, we’ll set up a new Flutter project and install the Stripe Flutter SDK package.

Navigate into your work directory and add the code below to initialize a new Flutter project:

flutter create stripe_app

Once initialization is complete, open either your Android emulator or iOS Simulator. Navigate into the stripe_app folder and run the app with the command below:

cd stripe_app && flutter run 

Your app should look similar to the screenshot below:

Flutter Demo App Homepage

Next, let’s install the Stripe Flutter SDK and get started building our project. Navigate to your directory and copy and paste the code below in your terminal:

dart pub add flutter_stripe

Installation requirements

To avoid compatibility issues, you should set up your project to match the required specifications below.

Android

For an Android OS, you’ll need the following:

  • Android v5.0 (API level 21) or higher
  • Kotlin v1.5.0 or higher
  • A descendant of Theme.AppCompact for your activity
  • FlutterFragmentActivity in MainActivity.kt instead of FlutterActivity

iOS

The Stripe Flutter SDK is compatible with apps targeting iOS 11 and above.

To avoid build error, navigate to iOS settings and find the stripePublishableKey proj or Runner.xcworkspastripe publishable key. Set the deployment target for the app to 12.0:

Stripe Flutter SDK iOS App Setup

Building the payment screen

To communicate with the Stripe API from your Flutter app, copy the stripePublishableKey from the Stripe dashboard, navigate into the lib folder, create a new file called env. dart, and add the code below:

const stripePublishableKey =  "your_publishable_key";

The stripePublishableKey constants hold the value of your key. Next, let’s set up card payment for our application and add buttons for Apple Pay and Google Pay.

Adding card payment

The most popular payment option in Stripe is a credit or debit card. To build a basic card input, navigate into the lib folder and update the code in main. dart with the code below:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:stripe_app/.env.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // set the publishable key for Stripe - this is mandatory
  Stripe.publishableKey = stripePublishableKey;
  runApp(App());
}
class App extends StatelessWidget {
  const App({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "FLutter tripe",
      theme: ThemeData(
        primaryColor: Colors.green,
      ),
        home: PaymentScreen(),
      );
  }
}
// payment_screen.dart
class PaymentScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          CardField(
            onCardChanged: (card) {
              print(card);
            },
          ),
          TextButton(
            onPressed: () async {
              // create payment method
              final paymentMethod =
                  await Stripe.instance.createPaymentMethod(PaymentMethodParams.card());
            },
            child: Text('pay'),
          )
        ],
      ),
    );
  }
}

In the code block above, we import the Flutter Stripe SDK and the .env.dart file. Then, we initialize Stripe with the StripePublishableKey that we created earlier. PaymentScreen returns a scaffold for both the payment input filed and the button.

At this point, your app should look similar to the screenshot below:

Card Payment Setup Stripe Flutter

Apple Pay plugin

The SDK is shipped with built-in support for pay plugins, including Apple Pay and Google Pay. The code snippet below creates an Apple Pay button:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:stripe_app/.env.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // set the publishable key for Stripe - this is mandatory
  Stripe.publishableKey = stripePublishableKey;
  runApp(App());
}
class App extends StatelessWidget {
  const App({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "FLutter tripe",
      theme: ThemeData(
        primaryColor: Colors.green,
      ),
        home: ApplePay(),
      );
  }
}
class ApplePay extends StatefulWidget {
  @override
  _ApplePayState createState() => _ApplePayState();
}
class _ApplePayState extends State<ApplePay> {
  @override
  void initState() {
    Stripe.instance.isApplePaySupported.addListener(update);
    super.initState();
  }
  @override
  void dispose() {
    Stripe.instance.isApplePaySupported.removeListener(update);
    super.dispose();
  }
  void update() {
    setState(() {});
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          if (Stripe.instance.isApplePaySupported.value)
            Padding(
              padding: EdgeInsets.all(16),
              child: ApplePayButton(
                onPressed: _handlePayPress,
              ),
            )
          else
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: Text('Apple Pay is not available in this device'),
            ),
        ],
      ),
    );
  }
}

Future<void> _handlePayPress() async {
  try {

  } catch (e) {
  }
}

The ApplePay class returns a scaffold of the button and a _handlePayPress function that is fired each time the button is pressed. Recall that the Stripe Flutter SDK is shipped with Dart APIs that handle events and responses. However, you can create custom event handlers like we did with the _handlePayPress method.

Now, your app should look like the following screenshot:

Apple Pay Setup Stripe Flutter

Google Pay plugin

Before we create the Google Pay button, let’s install the flutter pay package:

flutter pub add pay

On Installation complete, replace the code in main.dart with the code below to create the Google Pay button:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:pay/pay.dart';
import 'package:stripe_app/.env.dart';
import 'package:pay/pay.dart' as pay;
const _paymentItems = [
  pay.PaymentItem(
    label: 'Total',
    amount: '108.99',
    status: pay.PaymentItemStatus.final_price,
  )
];
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // set the publishable key for Stripe - this is mandatory
  Stripe.publishableKey = stripePublishableKey;
  runApp(App());
}
class App extends StatelessWidget {
  const App({Key key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "FLutter tripe",
      theme: ThemeData(
        primaryColor: Colors.green,
      ),
        home: GooglePay(),
      );
  }
}
class GooglePay extends StatefulWidget {
  @override
  _GooglePayState createState() => _GooglePayState();
}
class _GooglePayState extends State<GooglePay> {
  @override
  void initState() {
    Stripe.instance.isApplePaySupported.addListener(update);
    super.initState();
  }
  @override
  void dispose() {
    Stripe.instance.isApplePaySupported.removeListener(update);
    super.dispose();
  }
  void update() {
    setState(() {});
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          if (Stripe.instance.isApplePaySupported.value)
            Padding(
              padding: EdgeInsets.all(16),
              child: GooglePayButton(
              paymentConfigurationAsset: 'google_pay_payment_profile.json',
              paymentItems: _paymentItems,
              style: GooglePayButtonStyle.black,
              type: GooglePayButtonType.pay,
              margin: const EdgeInsets.only(top: 16),
              onPaymentResult: onGooglePayResult,
              loadingIndicator: const Center(
                child: CircularProgressIndicator(),
              ),
                onPressed: () async {
                }
              ),
            )
          else
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: Text('Apple Pay is not available in this device'),
            ),
        ],
      ),
    );
  }
}

Future<void> onGooglePayResult(paymentResult) async {
    try {

  } catch (e) {
  }
  }

In the code above, we imported the pay package that we installed earlier, created a _paymentItems constant to hold our payment details, then set the value of paymentItems in the GoogleButton to _paymentItems.

Adding assets to your application requires creating a new section. Create a new folder named assets in the root directory of your project, then create a new file called google_pay_payment_profile.json. Finally, enable assets in pubspec.yaml. Note that paymentConfigurationAsset is required:

Google Pay Configuration Stripe Flutter

Stripe query and response operations

The Stripe Flutter SDK has functions that are called for specific query and response operations when sending and receiving data via the Stripe API.

  • fetchPaymentIntentClientSecret: returns a client’s secret from the backend
  • confirmApplePayPayment: confirms Apple payment
  • confirmPaymentMethod: confirms the payment method by requiring clientSecret and payment details

Conclusion

The Stripe Flutter SDK is an easy and secure package for integrating and accepting payment in your Flutter app. In this tutorial, we explored Stripe’s features and capabilities, learning what makes it a popular choice for developers. We covered the required steps for setting up a Flutter application with Stripe, then added debit card payment and buttons for Apple Pay and Google Pay.

The Stripe Flutter SDK is a good choice anytime you need to add payment options in a mobile application. I hope you enjoyed this tutorial!

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Emmanuel Etukudo I am a full-stack developer with more than five years of experience, with a preference for JavaScript, Node.js, Go, React, Redux, and MongoDB.

Testing accessibility with Storybook

One big challenge when building a component library is prioritizing accessibility. Accessibility is usually seen as one of those “nice-to-have” features, and unfortunately, we’re...
Laura Carballo
4 min read

Leave a Reply