Stripe Payment Integration in Flutter

0

Stripe Payment Integration in Flutter app enables seamless and secure payment processing across iOS and Android platforms. This guide will walk through each step to set up Stripe, configure your Flutter app, and implement payment features with best practices.

Step 1: Create a Stripe Account

  • Sign up for a Stripe account at stripe.com.
  • From the Stripe Dashboard, obtain your Publishable Key and Secret Key. These keys are essential for connecting your Flutter app to Stripe’s payment backend.

Step 2: Add Flutter Stripe Dependencies

  • Add the official flutter_stripe package for Stripe SDK integration and the http package for network requests.
  • In pubspec.yaml add:
dependencies:
  flutter_stripe: ^12.0.2  # Use the latest version
  http: ^1.5.0

Next, don’t forget to install the dependencies after adding them.

Step 3: Configure Stripe for iOS and Android

For Android, this plugin requires several changes to be able to work on Android devices. Please make sure you follow all these steps:

  1. Use Android 5.0 (API level 21) and above.
  2. Use Kotlin version 1.8.0 and above: example
  3. Requires Android Gradle plugin 8 and higher
  4. Using a descendant of Theme.AppCompat for your activity: exampleexample night theme
  5. Using an up-to-date Android gradle build tools version: example and an up-to-date gradle version accordingly: example
  6. Using FlutterFragmentActivity instead of FlutterActivity in MainActivity.ktexample
  7. Add the following rules to your proguard-rules.pro file: example
-dontwarn com.stripe.android.pushProvisioning.PushProvisioningActivity$g
-dontwarn com.stripe.android.pushProvisioning.PushProvisioningActivityStarter$Args
-dontwarn com.stripe.android.pushProvisioning.PushProvisioningActivityStarter$Error
-dontwarn com.stripe.android.pushProvisioning.PushProvisioningActivityStarter
-dontwarn com.stripe.android.pushProvisioning.PushProvisioningEphemeralKeyProvider
# Keep Stripe classes
-keep class com.stripe.** { *; }
  1. Next, rebuild the app, as the above changes don’t update with hot reload.

These changes are needed because the Android Stripe SDK requires the use of the AppCompat theme for its UI components and the Support Fragment Manager for the Payment Sheets

For IOS, Compatible with apps targeting iOS 13 or above.
To upgrade your iOS deployment target to 13.0, you can either do so in Xcode under your Build Settings or by modifying IPHONEOS_DEPLOYMENT_TARGET in your project.pbxproj directly. Especially, you will also need to update your Podfile:

platform :ios, '13.0'

For card scanning, add the following to your Info.plist:

<key>NSCameraUsageDescription</key>
<string>Scan your card to add it automatically</string>
<key>NSCameraUsageDescription</key>
<string>To scan cards</string>

Step 4: Initialize Stripe in Flutter

Initialize Stripe in your Flutter app entry point (e.g., main.dart) with your publishable key and merchant ID:

import 'package:flutter_stripe/flutter_stripe.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Stripe.publishableKey = "your-publishable-key";
  Stripe.merchantIdentifier = "merchant.com.yourapp"; // For Apple Pay
  runApp(MyApp());
}
  • This step sets up the Stripe SDK to communicate with your Stripe account.

Step 5: Build the PaymentSheet flow in Flutter

lib/stripe/stripe_service.dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dio/dio.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:hotspots/core/secret/stripe_key.dart';

final stripePaymentProvider = Provider((ref) => StripePaymentService());

class StripePaymentService {
  final Dio _dio = Dio();

  Future<void> initPaymentSheet({
    required String amount,
    required String currency,
    required String merchantName,
  }) async {
    try {
      final paymentIntent = await _createPaymentIntent(amount, currency);

      await Stripe.instance.initPaymentSheet(
        paymentSheetParameters: SetupPaymentSheetParameters(
          paymentIntentClientSecret: paymentIntent['client_secret'],
          merchantDisplayName: merchantName,
          style: ThemeMode.light,
        ),
      );
    } catch (e) {
      rethrow;
    }
  }

  Future<void> presentPaymentSheet() async {
    await Stripe.instance.presentPaymentSheet();
  }

  Future<Map<String, dynamic>> _createPaymentIntent(
    String amount,
    String currency,
  ) async {
    final body = {
      'amount': (int.parse(amount) * 100)
          .toString(), // Stripe accepts amount in cents
      'currency': currency,
      'payment_method_types[]': 'card',
    };

    final response = await _dio.post(
      'https://api.stripe.com/v1/payment_intents',
      data: body,
      options: Options(
        headers: {
          'Authorization': 'Bearer $secretKey',
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      ),
    );

    return response.data;
  }
}

 

lib/stripe/pay_through_stripe_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hotspots/stripe/stripe_service.dart';

class PayScreen extends ConsumerWidget {
  const PayScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final stripeService = ref.read(stripePaymentProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('Stripe Payment')),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              await stripeService.initPaymentSheet(
                amount: '10',
                currency: 'usd',
                merchantName: 'WTF Code',
              );

              await stripeService.presentPaymentSheet();

              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text("Payment successful")),
              );
            } catch (e) {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text("Error: $e")));
            }
          },
          child: const Text('Pay \$10'),
        ),
      ),
    );
  }
}

In this article and video tutorial, we integrate Stripe payments in Flutter using test mode for learning purposes only. Additionally, this is not the best practice — in real apps, you must store your Stripe secret key on the backend, not in the frontend.

Step 6: Create Payment Intent on Server (Secure way to store a secret key)

  • For security, create a backend (Firebase Function, Node.js, Python, etc.) endpoint to generate a Payment Intent on Stripe using your secret key.
  • The Flutter app requests the client secret from this backend to confirm payments.
  • Example backend endpoint returns client secret for Flutter app.

This guide covers everything from Stripe Payment Integration in Flutter. Starting from  Stripe account setup through to Flutter code implementation and testing, enabling a smooth payment experience with a simple, secure integration for both platforms.

Visit on Google_Sign_In latest version 7.1.1

Previous articleHow to Integrate Google Maps in Flutter
Next articleFlutter Flavors Setup For Android and IOS

LEAVE A REPLY

Please enter your comment!
Please enter your name here