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 http for making a network call to fetch client secret.Provide the latest dependency versions so as to avoid any 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_51MWx8OAVMyklfe3CsjEzA1CiiY0XBTlHYbZ8jQlGtVFIwQi4aNeGv8J1HUw4rgSavMTLzTwgn0XRlwoTVRFXyu2h00mRUeWmAf"; 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 below the complete code for stripe mobile payments online transaction which is secure, quick, easy payment.
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 :
Add this code to existing file in android directory.
package com.example.flutter_stripe_example import io.flutter.embedding.android.FlutterFragmentActivity class MainActivity: FlutterFragmentActivity() { }
Stripe Payment Output :
If you have any query’s in this tutorial on flutter Stripe Payments do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.