Facebook Twitter Instagram
    DeepCrazyWorld
    Facebook Twitter Instagram Pinterest YouTube
    • FLUTTER
      • FLUTTER APP
        • QRCode
        • Quiz App
        • Chat GPT
        • PDF App
        • News App
        • Fitness App
        • Weather App
        • BMI Calculator
        • GAME APP
        • Ecommerce App
        • wallpaper App
        • Finance app
        • Chat App
        • Wallet App
        • Taxi App
        • Quran app
        • Music player app
      • FLUTTER UI
        • Splash Screen
        • Onboarding Screen
        • Login Screen
        • Card Design
        • Drawer
    • PROJECT
      • Android Projects
      • College Projects
      • FLUTTER APP
      • Project Ideas
      • PHP Projects
      • Python Projects
    • SOURCE CODE
    • ANDROID
      • ANDROID APP
      • GAME APP
      • ANDROID STUDIO
    • MCQ
      • AKTU MCQ
        • RPA MCQ
        • COA MCQ
        • HPC MCQ
        • SPM MCQ
        • Renewable Energy All MCQ
        • Data Compression MCQ
        • Data Structure MCQ
        • Digital Image Processing MCQ
        • Software Engineering MCQ
        • Machine Learning MCQ
        • Artificial Intelligence MCQ
      • D PHARMA MCQ
        • Pharmaceutics – I MCQ
        • Pharmacognosy MCQ
        • Pharmaceutical Chemistry MCQ
        • Biochemistry and Clinical Pathology MCQ
        • Human Anatomy and Physiology MCQ
        • Heath Education and Community Pharmacy MCQ
    • INTERVIEW QUESTIONS
      • Flutter Interview Questions
      • INTERVIEW QUESTIONS
      • Python Interview Questions
      • Coding ninjas solution
    • MORE
      • WORDPRESS
        • SEO
        • TOP 10 WORDPRESS THEME
      • PRODUCTIVITY
      • Program
      • QUOTES
    DeepCrazyWorld
    Home»FLUTTER»Stripe Payment gateway integration in Flutter 2023
    FLUTTER

    Stripe Payment gateway integration in Flutter 2023

    DeepikaBy DeepikaJanuary 13, 2023Updated:February 19, 2023No Comments7 Mins Read

    Hello there, In this articles we are going to explan about Integrate Payment in Flutter with Stripe after successfully done payment with test mode and live mode. Nevertheless, I became aware that I hadn’t published anything in a while and promised to write at least two pieces in December and to be more consistent going forward. I thus request that each and every one of my readers hold me responsible.

    <img decoding=

    The topic of today’s article is using Stripe to manage payments in Flutter Stripe Payment gateway integration in Flutter 2023. Payment was one of those functionalities, and they naturally intended to utilise Stripe. I, on the other hand, had never integrated Stripe into Flutter before, but I wouldn’t let a challenge get the better of me, so I accepted the assignment and set to work conducting my research. I had to gather this information from a variety of sources, but I’ll do my best to make this post as informative as I can so you won’t have to look elsewhere for the answers to this question. Let’s get started; enough with the winding stories.

    via GIPHY

    Table of Contents

    Toggle
    • ABOUT STRIPE:
    • STEP 1:
    • STEP 2:
      • Flutter plugin add environment setup:
    • STEP 3:
      • main.dart
      • main.dart complete code
    • STEP 4:
      • HomePage.dart
    • STEP 5:
      • MainActivity.kt Change these line
    • STEP 6:
      • Change styles.xml files code for theme
    • Conclusion
    • Related Articles:
      • READ MORE

    ABOUT STRIPE:

    First, a little introduction to this fantastic payment system, Stripe. Millions of businesses, including Shopify, Instacart, and some of our major internet corporations like Google, Amazon, and others, utilise the Stripe payment gateway. They offer a straightforward and streamlined method for companies and their customers throughout the world to receive and transmit payments. They also provide further services like creating invoices, processing recurring payments, providing reports on finances that are intelligent and diagrammatic, and more.

    via GIPHY

    Demo watch now : Integrate Payment in Flutter with Stripe

    As a developer, I found Stripe’s ease of integration into a variety of stacks, the libraries that enable it, and its support for native payment methods like Apple and Google pay to be very intriguing.

    STEP 1:


    We would need to generate an API key from Stripe in order to begin. You would require setting up a Stripe account in order to achieve this. Log in to your dashboard now, switch to Test mode for integration and testing, and then select Developers > API Keys to view your API keys (Publishable and Secret Keys).

    Stripe Documentaion Official Site: https://stripe.com/docs/keys

    These are the Stripe Test Mode Secret Key and Publishable (use these key for Payment gateway testing)

    NOTE: ADD OWN TEST/LIVE SECRET KEY AND Publishable KEY

    Secret:
    sk_test_tR3PYbcVNZZ796tH88S4VQ2u
    
    
    Publishable:
    pk_test_51BTUDGJAJfZb9HEBwDg86TN1KNprHjkfipXmEDMb0gSCassK5T3ZfxsAbcgKVmAIXF7oZ6ItlZZbXO6idTHE67IM007EwQ4uN3

    STEP 2:

    Flutter plugin add environment setup:

    The following packages should be included in your dependencies:

    flutter_stripe: ^7.0.0
    flutter_dotenv: ^5.0.2
    http: ^0.13.5

    Flutter PUB.DEV , Add these plugin updated version from flutter official site.

    1. Flutter Stripe : https://pub.dev/packages/flutter_stripe
    2. flutter_dotenv: https://pub.dev/packages/flutter_dotenv
    3. http: https://pub.dev/packages/http

    The flutter stripe package will be used by us because it relieves the stress of having to create our own payment modal by giving us a lovely one that already has all the fields and customization we require. Additionally, it enables you to scan your card to retrieve its details and has dark mode (wink wink). To set up the extra configurations needed for the flutter stripe package on Android, go to their instructions here.

    To communicate with the Stripe API, we’ll be using http, you may handle your API calls using dio or any other package of your choice if you like.

    To safeguard our Stripe Keys, there is also the flutter dotenv package. To keep them secure and protect you and your users from danger, I advise storing your keys in a.env file. How will we go about doing that?

    Create a .env file

    assets folder like this:

    Put your Stripe private key in your.env file in the following manner:

    STRIPE_SECRET = sk_test_tR3PYbcVNZZ796tH88S4VQ2u

    Add your .env path to your assets in pubspec.yaml code

    STRIPE_SECRET = sk_test_tR3PYbcVNZZ796tH88S4VQ2u
    assets:
    - assets/.env

    Add your .env to gitignore

    
    #Dotenv
    .env
    

    STEP 3:

    main.dart

    Add here in main.dart , add publishableKey (Test Mode for testing purpose and Live url for Original Payment)

     Stripe.publishableKey = "pk_test_24PsRoB2O46Bxxxxxxxxxxxxxxxxxxxxxxxx";
    
      await dotenv.load(fileName: "assets/.env");
    
    #Dotenv
    .env
    

    main.dart

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      Stripe.publishableKey = "pk_test_51BTUDGJAJfZb9HEBwDg86TN1KNprHjkfipXmEDMb0gSCassK5T3ZfxsAbcgKVmAIXF7oZ6ItlZZbXO6idTHE67IM007EwQ4uN3";
    
      //Load our .env file that contains our Stripe Secret key
      await dotenv.load(fileName: "assets/.env");
    
       runApp(const MyApp());
        }

    main.dart complete code

    import 'package:flutter/material.dart';
        
    void main()  async {
      WidgetsFlutterBinding.ensureInitialized();
    
      Stripe.publishableKey = "pk_test_51BTUDGJAJfZb9HEBwDg86TN1KNprHjkfipXmEDMb0gSCassK5T3ZfxsAbcgKVmAIXF7oZ6ItlZZbXO6idTHE67IM007EwQ4uN3";
    
      //Load our .env file that contains our Stripe Secret key
      await dotenv.load(fileName: "assets/.env");
    
          runApp(const MyApp());
        }
        
        class MyApp extends StatelessWidget {
          const MyApp({Key? key}) : super(key: key);
        
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              title: 'Stripe payment gateway in flutter',
              theme: ThemeData(primarySwatch: Colors.blue),
              home: const HomePage(),
            );
          }
        }

    STEP 4:

    HomePage.dart

    import 'package:flutter/material.dart';
        
    class HomePage extends StatelessWidget {
          const HomePage({Key? key}) : super(key: key);
        
          @override
          Widget build(BuildContext context) {
            return Scaffold(
              body: Container(
                child:  Center(child: Text("Hello World!")),
              ),
            );
          }
        }

    Import dependency

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

    makePayment flunction in onTap

                           onTap: () async {
                            await makePayment();

    Full code of container button

        child: InkWell(
                          onTap: () async {
                            await makePayment();
                          },
                          Container(
                            height: 50,
                            width: 90,
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(5),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(0.5),
                                  spreadRadius: 2,
                                  blurRadius: 2,
                                  offset:
                                      Offset(0, 2), // changes position of shadow
                                ),])),
                                ),
          

    makePayment Function

      Map<String, dynamic>? paymentIntent;
    
      Future<void> makePayment() async {
        try {
          paymentIntent = await createPaymentIntent('2', 'USD');
    
          //STEP 2: Initialize Payment Sheet
          await Stripe.instance
              .initPaymentSheet(
                  paymentSheetParameters: SetupPaymentSheetParameters(
                      paymentIntentClientSecret: paymentIntent![
                          'client_secret'], //Gotten from payment intent
                      style: ThemeMode.dark,
                      merchantDisplayName: 'Ikay'))
              .then((value) {});
    
          //STEP 3: Display Payment sheet
          displayPaymentSheet();
        } catch (err) {
          throw Exception(err);
        }
      }
    
      displayPaymentSheet() async {
        try {
          await Stripe.instance.presentPaymentSheet().then((value) {
            showDialog(
                context: context,
                builder: (_) => AlertDialog(
                      content: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.check_circle,
                            color: Colors.green,
                            size: 100.0,
                          ),
                          SizedBox(height: 10.0),
                          Text("Payment Successful!"),
                        ],
                      ),
                    ));
    
            paymentIntent = null;
          }).onError((error, stackTrace) {
            throw Exception(error);
          });
        } on StripeException catch (e) {
          print('Error is:---> $e');
          AlertDialog(
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: const [
                    Icon(
                      Icons.cancel,
                      color: Colors.red,
                    ),
                    Text("Payment Failed"),
                  ],
                ),
              ],
            ),
          );
        } catch (e) {
          print('$e');
        }
      }
    
      createPaymentIntent(String amount, String currency) async {
        try {
          //Request body
          Map<String, dynamic> body = {
            'amount': calculateAmount(amount),
            'currency': currency,
          };
    
          //Make post request to Stripe
          var response = await http.post(
            Uri.parse('https://api.stripe.com/v1/payment_intents'),
            headers: {
              'Authorization': 'Bearer ${dotenv.env['STRIPE_SECRET']}',
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: body,
          );
          return json.decode(response.body);
        } catch (err) {
          throw Exception(err.toString());
        }
      }
    
      calculateAmount(String amount) {
        final calculatedAmout = (int.parse(amount)) * 100;
        return calculatedAmout.toString();
      }
    }

    STEP 5:

    MainActivity.kt Change these line

    package com.app.StripeApp
    
    import io.flutter.embedding.android.FlutterActivity
    import io.flutter.embedding.android.FlutterFragmentActivity
    
    class MainActivity: FlutterFragmentActivity() {
    }
    <img loading=
    Change MainActivity.kt File with these code – integration stripe payment gateway

    STEP 6:

    Change styles.xml files code for theme

    <img loading=
    change style.xml for theme – stripe payment gateway with flutter

    Conclusion

    The integration of Stripe into your Flutter application is complete.

    All you have to do to launch your app is switch from Test mode to Live mode on your dashboard and adhere to Stripe’s guidelines.

    Please let me know if you have any questions or comments, and don’t forget to give this post a thumbs up if you found it helpful.

    DONE!

    via GIPHY

    Get the whole source code right here.

    Related Articles:

    • How to Install Flutter in windows 10
    • How to Setup Space Between Elements In Flutter 
    • Flutter Card Widget with Example
    • Integrating an API into a Flutter – Working with REST APIs
    • Create a simple splash screen in Flutter
    • Android Projects with Source Code
    • Flutter Interview Questions
    • School Database Management System Project 
    • Create A Simple Splash Screen UI design
    • Create Login Page UI Design and Animation For Flutter
    • Flutter interview questions 2023

    READ MORE

    Share. Facebook Twitter LinkedIn WhatsApp Telegram Pinterest Reddit Email
    Previous ArticleHow to Make Car Racing Game App with Android Studio
    Next Article Top 50+ Flutter Interview Questions in 2023

    Related Posts

    Implementing a Dynamic FAQ Screen UI in Flutter Using ExpansionTile

    FLUTTER 5 Mins Read

    Animated Backgrounds in Flutter: A Complete Guide

    FLUTTER 4 Mins Read

    How to make custom BottomNavigationBar in flutter with source code

    BottomNavigationBar 4 Mins Read

    How to Make a ToDo App with Flutter with source Code StepWise in 2024

    FLUTTER 4 Mins Read

    Leave A Reply Cancel Reply

    Recent Posts
    • Implementing a Dynamic FAQ Screen UI in Flutter Using ExpansionTile March 29, 2025
    • Creating an Instruction UI Screen in Flutter Application March 29, 2025
    • Animated Backgrounds in Flutter: A Complete Guide March 15, 2025
    • How to make Diary App using flutter stepwise using getx August 31, 2024
    • How to Create Music Player UI screen with fully functional in flutter August 30, 2024
    • How to make ListView Builder Ui in flutter with Source Code August 29, 2024
    • Create a TabBar View in flutter with fully functional stepwise August 28, 2024
    • How to create TabBar view in flutter with source code step wise August 27, 2024
    • How to make Heart rate measure app with Flutter stepwise August 26, 2024
    • How to make ChatGpt App in flutter with source code Stepwise August 25, 2024
    Facebook Twitter Instagram Pinterest YouTube
    • About
    • Contact
    • Disclaimer
    • Privacy Policy
    Copyright by DeepCrazyWorld © 2025

    Type above and press Enter to search. Press Esc to cancel.