Stripe Payment Integration in Flutter: A Step-by-Step Guide

Stripe Payment :

Stripe Payment, In this blog we will be going through stripe implementation in flutter app. Starting from account creation gathering keys required for initialisation of payment sheet and so on.

All the minor aspects are covered in this tutorial make sure you follow every step to make a successful payment at the end of the tutorial.

In stripe the important steps like gathering publishable key, secret key so as to generate client secret which creates a payment sheet for final payment.

We can make us of card based payments, Google-Pay, Apple-Pay based payments and many more using stripe.

This tutorial will form a complete guide for e-commerce related mobile app for making checkout, secure transactions in your app.

 

Stripe Payment Video Tutorial :

Go through the complete video tutorial playlist on stripe implementation.

 

pubspec.yaml :

Add the stripe dependency and the ‘http’ package for facilitating network calls to retrieve the client secret. Make sure to use the latest versions of dependencies to mitigate potential issues.

flutter_stripe: ^7.0.0
http: 0.13.5

 

main.dart :

import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'homescreen.dart';

void main() async {
  //Initialize Flutter Binding
  WidgetsFlutterBinding.ensureInitialized();

  Stripe.publishableKey =
  "pk_test_51MWx8OAVMyklfe3CsjEzA1CiiY0XBTlQlGi4aNeGv8J1HUw4rgSavMTLzTwgn0XRlwoTVRFXyu2h00mRUeWmAf";

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      //initial route
      home: HomeScreen(),
    );
  }
}

 

homescreen.dart :

In HomeScreen class we can start integrating stripe payment gateway by making a api call to fetch client secret.

 

Make an api call as below by providing the amount and currency

createPaymentIntent(String amount, String currency) async {
  try {
    Map<String, dynamic> body = {
      'amount': amount,
      'currency': currency,
    };

    var response = await http.post(
      Uri.parse('https://api.stripe.com/v1/payment_intents'),
      headers: {
        'Authorization': 'Bearer sk_test_51MWx8OAVMyklfe3C3gP4wKOhTsRdF6r1PYhhg1PqupXDITMrV3asj5Mmf0G5F9moPL6zNfG3juK8KHgV9XNzFPlq00wmjWwZYA',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: body,
    );
    return json.decode(response.body);
  } catch (err) {
    throw Exception(err.toString());
  }
}

 

Initialise payment sheet once the api call is successful and client secret is received.

await Stripe.instance
    .initPaymentSheet(
    paymentSheetParameters: SetupPaymentSheetParameters(
        paymentIntentClientSecret: paymentIntent![
        'client_secret'], //Gotten from payment intent
        style: ThemeMode.light,
        merchantDisplayName: 'Abhi',
        googlePay: gpay))
    .then((value) {});

Now finally display payment sheet and make the payment and observe the output.

displayPaymentSheet() async {
  try {
    await Stripe.instance.presentPaymentSheet().then((value) {
      print("Payment Successfully");
    });
  } catch (e) {
    print('$e');
  }
}

 

G-Pay Integration :

Now add the google pay integration to the existing payment sheet.

 

var gpay = PaymentSheetGooglePay(merchantCountryCode: "GB",
    currencyCode: "GBP",
    testEnv: true);

 

Stripe Payment Full Code :

Find the full code snippet for secure, efficient, and user-friendly Stripe mobile payment integration below, ensuring a seamless online transaction experience

 

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:http/http.dart' as http;

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Map<String, dynamic>? paymentIntent;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Stripe Payment'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextButton(
              child: const Text('Buy Now'),
              onPressed: () async {
                await makePayment();
              },
            ),
          ],
        ),
      ),
    );
  }

  Future<void> makePayment() async {
    try {
      paymentIntent = await createPaymentIntent('10000', 'GBP');

      var gpay = PaymentSheetGooglePay(merchantCountryCode: "GB",
          currencyCode: "GBP",
          testEnv: true);

      //STEP 2: Initialize Payment Sheet
      await Stripe.instance
          .initPaymentSheet(
          paymentSheetParameters: SetupPaymentSheetParameters(
              paymentIntentClientSecret: paymentIntent![
              'client_secret'], //Gotten from payment intent
              style: ThemeMode.light,
              merchantDisplayName: 'Abhi',
              googlePay: gpay))
          .then((value) {});

      //STEP 3: Display Payment sheet
      displayPaymentSheet();
    } catch (err) {
      print(err);
    }
  }

  displayPaymentSheet() async {
    try {
      await Stripe.instance.presentPaymentSheet().then((value) {
        print("Payment Successfully");
      });
    } catch (e) {
      print('$e');
    }
  }

  createPaymentIntent(String amount, String currency) async {
    try {
      Map<String, dynamic> body = {
        'amount': amount, 
        'currency': currency,
      };

      var response = await http.post(
        Uri.parse('https://api.stripe.com/v1/payment_intents'),
        headers: {
          'Authorization': 'Bearer sk_test_51MWx8OAVMyklfe3C3gP4wKOhTsRdF6r1PYhhg1PqupXDITMrV3asj5Mmf0G5F9moPL6zNfG3juK8KHgV9XNzFPlq00wmjWwZYA',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: body,
      );
      return json.decode(response.body);
    } catch (err) {
      throw Exception(err.toString());
    }
  }


}

 

manifest.xml :

Add the below meta data to manifest file.

<meta-data
  android:name="io.flutter.embedding.android.NormalTheme"
  android:resource="@style/Theme.AppCompat"
  />

 

 

MainActivity.kt :

Insert the following code into the pre-existing file located in the Android directory of your project.

package com.example.flutter_stripe_example

import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity: FlutterFragmentActivity() {
}

 

Stripe Payment Output :

Please follow the step-by-step guide provided in the tutorial below to implement Stripe Payments in your Flutter application.

 

If you have any questions about the Flutter Stripe Payments tutorial, please feel free to ask in the comment section below. If you found the tutorial helpful, we appreciate your likes and shares for more interesting updates.

Show Buttons
Hide Buttons
Read previous post:
Flutter OneSignal Deeplink Implementation

Flutter Onesignal Deeplinks : Flutter onesignal deeplink concept is explained in this blog with OneSignal. Deep linking enables you to improve...

Close