Integrate Payment in Flutter with Stripe

Learn via video courses
Topics Covered

Overview

Stripe is a powerful payment platform widely used for processing online payments in Flutter apps. It offers a comprehensive suite of APIs and tools, allowing developers to seamlessly integrate payment functionality into their applications. With support for various payment methods, Stripe simplifies the payment process for both businesses and customers. The Flutter Stripe library acts as a bridge between Flutter and Stripe, providing convenient methods and classes to interact with the Stripe API. By leveraging Stripe's secure infrastructure and developer-friendly documentation, developers can easily create payment forms, process payments, handle subscriptions, and implement advanced features like coupons and refunds.

Installing and Configuring Stripe

Installing and configuring Flutter Stripe library for the platform you wanna integrate it with is essential for it to run smoothly and establish connection:

Android

To configure Stripe for Android, begin by adding your Stripe publishable key to the Android manifest file in your Flutter project. You can obtain the publishable key from your Stripe account dashboard. Open the AndroidManifest.xml file and add the following metadata element inside the <application> tag:

iOS

For iOS configuration, you need to modify the AppDelegate.swift file in your Flutter project. Import the flutter_stripe package and add the following lines of code inside the application(_:didFinishLaunchingWithOptions:) method:

Web

Stripe support for Flutter web is currently in an experimental phase. To enable Stripe for web, you need to include the Stripe JavaScript library in your web app. You can refer to the official documentation of flutter_stripe and the Stripe website for detailed instructions on setting up Stripe for web in Flutter.

By adding the correct keys and configurations, you establish a secure connection and enable your app to process payments seamlessly.

Setting up a Stripe Account

It is mandatory for you to setup a develoeper Stripe account in order to integrate your stripe API to any application or service, Here's how you can do it:

  1. Visit the Stripe website: Visit the official Stripe website at stripe.com.
  2. Sign up or log in: If you're new to Stripe, click on the "Get Started" or "Sign up" button to create a new account. If you already have a Stripe account, simply log in using your credentials.
  3. Provide business details: Stripe requires you to provide information such as your business name, address, contact information, and website URL. Fill in these details accurately to ensure proper identification and compliance.
  4. Verify your email address: Stripe will send a verification email to the address you provided during registration. Click on the verification link in the email to confirm your email address.
  5. Set up your business profile: You'll be prompted to set up your business profile.
  6. Configure payment settings: In your Stripe dashboard, navigate to the "Payments" or "Settings" section to configure your payment settings.
  7. Obtain publishable and secret keys: To integrate Stripe into your Flutter app, you need to obtain your publishable key and secret key. These keys serve as the authentication mechanism between your app and Stripe. In your Stripe dashboard, go to the "Developers" or "API Keys" section to find your keys. Copy and securely store these keys, as you'll need them during the app integration process.
  8. Test mode vs. live mode: Stripe offers a test mode that allows you to simulate payment transactions without charging any actual funds. Toggle it on to be safe during testing period.

If you run into any issues or have additional requirements, you can use Stripe's documentation and guidelines to understand any additional requirements or features specific to your business model or country of operation.

Building a Payment Form

To integrate payment functionality into your Flutter app with Flutter Stripe library, you'll need to build a payment form where users can enter their payment details. The payment form is responsible for collecting the necessary information from the user, such as card number, expiration date, CVC, and billing details.

Here's how you can do it:

  • Collecting Card Information: The payment form should provide input fields for the user to enter their card details. These typically include the card number, expiration date, and CVC
  • Handling Validation: Validate the user's input to ensure it meets the required criteria. For example, you can check for a valid card number format and more.
  • Billing Details: Collect any required billing details from the user, such as their name, email address, and billing address.
  • Card Input Formatting: Enhance the user experience by formatting the card number input field dynamically. For example, you can automatically insert spaces after every four digits to match the standard card number format.
  • Real-time Validation: Consider implementing real-time validation as the user enters their card details. This can include checking the card's brand and displaying corresponding card icons etc.

You can build a payment form with above functionality by leveraging the widgets that Flutter provides such as TextField, TextEdittingController, Icons and more.

Processing Payments with Stripe API

Once you have collected the necessary payment details from the user, you need to process the payments using the Stripe API.

Here's a overview of how to process payments using the Stripe API in your Flutter app:

Create a Payment Intent

Create a payment intent on the server-side. A payment intent represents the transaction and contains the necessary information such as the amount, currency, and payment method.

In your Flutter app, make an API call to your server with the required parameters to create a payment intent. You can use the Stripe API's /v1/payment_intents endpoint to accomplish this.

Note: Ensure that you include your Stripe secret key in the request headers for authentication.

Confirm the Payment Intent

Once the payment intent is created, you need to confirm it to finalize the payment. This step verifies that the payment details provided by the user are valid and initiates the actual charge.

To confirm the payment intent, make an API call to the Stripe API's /v1/payment_intents/{payment_intent_id}/confirm endpoint, passing the payment intent ID and any additional required parameters. The confirmation process will depend on the payment method used.

Handle Payment Status

After confirming the payment intent, you should check the status of the payment to determine whether it was successful or if there was an error.

The payment intent's status will be updated by Stripe based on the outcome of the payment attempt. Common payment status values include "succeeded" for successful payments and "requires_payment_method" or "requires_action" for incomplete or failed payments.

Depending on the status, you can take appropriate actions in your Flutter app, such as showing a success message or handling any necessary user actions or error cases.

Testing Payments

Stripe provides test modes and test API keys to facilitate payment testing in a sandbox environment. Utilize test mode during development and testing to simulate payment transactions without charging any real funds. This ensures that your payment processing flow is functioning correctly before deploying to a production environment.

Handling Payment Flows and User Experience

  • Clear Payment Instructions: Provide clear instructions and guidance to users on how to complete the payment process.
  • Responsive Design: Optimize the payment form and UI elements for different screen sizes and orientations.
  • User-Friendly Input Fields: Implement user-friendly input fields that validate user input in real-time. Provide feedback and error messages for invalid entries.
  • Loading Indicators: Display loading indicators or progress bars during payment processing to keep users informed about the ongoing transaction.
  • Confirmation and Receipts: Provide clear confirmation messages once the payment is successfully processed.
  • Error Handling: Implement error handling mechanisms to handle payment failures and other unexpected scenarios.
  • Localization and Internationalization: If your app caters to a global audience, consider localizing the payment flow to support multiple languages, currencies, and country-specific payment methods.

Managing Subscriptions and Recurring Payments

Flutter Stripe library also comes packed with other robust features such as recurring payments and managing subscriptions. This allows you to offer subscription-based services and automate recurring payments for your users.

  • Plan Creation: You can create subscription plans on the Stripe Dashboard or programmatically through the Stripe API by defining the details of each plan with relevant information.

  • Customer Subscription Management: Stripe provides APIs to manage customer subscriptions. When a user subscribes to a plan, create a customer object in Stripe, associate the customer with their payment method, and subscribe them to the desired plan.

  • Payment Method Updates: Enable users to update their payment methods for recurring payments using the methods and APIs provided by Stripe.

  • Subscription Status and Expiration: Track the status of subscriptions, Stripe automatically handles subscription renewals, expirations, and cancellations.

  • Subscription Upgrades, Downgrades, and Add-ons: Utilize the Stripe API to modify subscriptions, calculate prorated amounts, and handle any necessary billing adjustments and enable users to upgrade, downgrade or add-on to the subscription.

  • Grace Periods and Dunning Management: Implement automated retry logic for failed payments, and use Stripe's dunning management tools to handle communication with customers regarding payment issues.

  • Subscription Metrics and Reporting: Stripe offers built-in subscription metrics and reporting tools to help you monitor key subscription-related metrics such as subscription growth, churn rates, revenue, and other important metrics.

  • Subscription Cancellation and Refunds: Stripe provides APIs to cancel subscriptions and handle any necessary refunds.

Implementing additional features like coupons, discounts, or refunds

In addition to processing payments, Flutter Stripe library also provides features that allow you to implement additional functionality such as coupons, discounts, and refunds within your Flutter app. These features can enhance the user experience and enable you to offer promotional offers or handle refund requests.

Here's a overview of implementing these features using the Stripe API:

Coupons and Discounts

  • Create coupons or discount codes in your Stripe dashboard or programmatically through the Stripe API.
  • Apply the coupon or discount code to the relevant charges or subscriptions using the appropriate API endpoint.
  • Calculate the discounted amount or adjust the pricing based on the applied coupon or discount.

Refunds

  • Identify the charge or subscription for which a refund is requested, either by retrieving the relevant payment details or by tracking the transaction in your app's database.
  • Use the Stripe API to initiate the refund by specifying the amount to be refunded and the reason for the refund.
  • Handle the response from the API to determine the status of the refund and update the relevant records in your app's database or user interface accordingly.

Managing Coupons and Discounts:

  • Stripe provides APIs and tools to manage and track coupons or discount codes. You can create, update, or delete coupons programmatically, retrieve coupon details, and track their usage.
  • Leverage these APIs to handle coupon management within your Flutter app, such as displaying active coupons, applying them to charges or subscriptions, and monitoring coupon usage and redemption rates.

Advanced Stripe features for specific business needs

Stripe offers a range of advanced features that cater to specific business needs, providing flexibility and customization options for payment processing in your Flutter app. Here are some notable advanced features offered by Stripe:

  • Connect Platform: Stripe Connect allows you to create and manage connected accounts, handle payments, and facilitate fund transfers between platform accounts and connected accounts.

  • Radar for Fraud Detection: Stripe's Radar is an advanced fraud detection and prevention system that leverages machine learning and customizable rules to identify and mitigate fraudulent activities.

  • Billing and Subscription Management: Stripe's Billing API gives you the ability to managing subscriptions, recurring billing, and invoicing. With the Billing API, you can automate invoice generation, manage customer subscriptions and more like pricing logic tailored to your business needs.

  • Account and Financial Reporting: Stripe provides comprehensive reporting tools and APIs that allow you to access financial data, generate detailed reports, and reconcile transactions.

  • Global Payment Support: With Stripe, you can localize your payment experience, and handle currency conversions seamlessly.

Usage

When it comes to accepting card payments in your Flutter app using Stripe, there are various methods and options available. Here's an overview of the two primary usage categories:

Card Payments

Stripe offers different ways to handle card payments within your app. You can choose the method that best suits your needs based on ease of use and functionality. Here are three common methods:

MethodEase of useDescription
Card FormMediumMulti-line card input form.
CardfieldMediumSingle-line card input field with more flexibility.
Payment SheetEasyRecommended method with localization, animations, and more.

Financial Connections

Stripe also allows you to establish financial connections within your app. This is particularly useful for platforms or marketplaces facilitating transactions between multiple parties.

With Stripe Connect, you can create and manage connected accounts, handle payments, and enable fund transfers between platform accounts and connected accounts. This feature provides flexibility and control over fees, payouts, and dispute management.

ExampleApp

Below is a ExampleApp we have built to demonstrate how you can use/integrate stripe Flutter library to your Flutter application.

The app is a simple payments app which allows you to make a payment using stripe

The code for the app looks like this: main.dart file:

The output of the application will look like this:

Stripe payment

You can find the entire source code of the application here: https://github.com/TRohit20/Flutter-Playground/tree/main/stripe_payments_app

Conclusion

  • Stripe's Flutter library enables seamless integration of payment functionality into your app, allowing you to accept card payments, manage subscriptions, and handle refunds.
  • Setting up a Stripe account is mandatory which involves obtaining API keys and configuring your account settings.
  • Building a payment form can be done using Stripe's Payment Sheet, Cardfield, or Card Form methods, depending on your design preferences and required functionality.
  • Processing payments with the Stripe API involves creating payment intents, handling payment method data, and confirming payments.
  • It's important to consider user experience and implement features such as error handling, localization, and customization for a smooth payment flow.
  • Managing subscriptions and recurring payments requires handling subscription lifecycles, payment method updates, and subscription status tracking.
  • Advanced Stripe features, such as coupons, discounts, and refunds, can be implemented to offer promotional offers and handle refund requests.
  • Remember to Handle Secrets such as safeguarding your Stripe API keys and other sensitive information. Avoid hardcoding secrets directly into your app's source code.
  • When processing payments, it's recommended to handle sensitive data on your server rather than client-side.
  • Set up and handle Stripe webhooks to receive real-time notifications about payment events, subscription changes, and other important updates.
  • Leverage Stripe's reporting tools and APIs to monitor key payment metrics, such as transaction volumes, success rates, and revenue.