Exploring the 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 pre-built 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.

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 user’s 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 your 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, as well as 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!

The post Exploring the Stripe Flutter SDK appeared first on LogRocket Blog.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Exploring the Stripe Flutter SDK

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.