6/recent/ticker-posts

Stripe Payment in Flutter

Stripe is a widely used payment gateway that provides businesses with a seamless way to accept and send payments. Trusted by major companies like Google and Amazon, Stripe offers a range of services, including card processing, recurring payments, financial analysis, and invoice generation. What sets Stripe apart for developers is its ease of integration and support for native payment methods such as Apple Pay and Google Pay. With Stripe, developers can leverage powerful libraries and resources to incorporate secure and reliable payment functionality into their applications.

Stripe’s versatility and robust infrastructure make it an ideal choice for developers seeking to enhance payment experiences. By integrating Stripe, businesses can offer their customers a smooth and convenient payment process while enjoying the benefits of comprehensive financial tools and reporting. With Stripe’s widespread adoption and seamless integration, developers can unlock new possibilities in managing transactions and delivering exceptional user experiences. Stripe’s developer-friendly approach empowers businesses to focus on their core offerings while relying on a trusted payment platform.

The provided tutorial demonstrates how to integrate Stripe payment functionality into a Flutter app.

Here's a description of the steps involved:

Step 1: Import Dependencies In your pubspec.yaml file, add the following dependencies:

dependencies:
flutter_stripe: ^7.0.0
http: ^0.13.5

Step 2: Changes in android → app → src → main → res → values → styles.xml file Update your styles.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->

<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while it's
running.This Theme is only used starting with V2 of Flutter's Android embedding. -->

<style name="NormalTheme" parent="Theme.MaterialComponents">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

Step 3: Change in android → app → src → main → res → values-night→ styles.xml Update your values-night/styles.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->

<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while it's
running.This Theme is only used starting with V2 of Flutter's Android embedding. -->

<style name="NormalTheme" parent="Theme.MaterialComponents">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>

Step 4: Minimum Version Requirement In your android/app/build.gradle file, make the following changes:

android {
compileSdkVersion 28
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.flutterstripepaymentdemo"
minSdkVersion 19
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
}

Step 5: Enable MultiDex To enable MultiDex, make sure the following dependencies are added in your android/app/build.gradle file:

android {
defaultConfig {
// ...
multiDexEnabled true
}
}
dependencies {
implementation 'androidx.multidex:multidex:2.0.1'
}

Step 6: Create Secret Key and Publish Key

  1. Go to the Stripe website at https://dashboard.stripe.com/.
  2. Log in to your Stripe account using your credentials.
stripe account

3. Once logged in, you will be redirected to the Stripe Dashboard.

4. click on the “Developers” tab. select “API Keys”.

5. On the API Keys page, you will find your publishable key .

6.To reveal your secret key, click on the “Reveal test key ” button next to the “Secret key” field.

Step 7 : Import Dependencies In your main.dart file, add the necessary import statements:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'dashboard.dart';

Step 8: Initialize Flutter Stripe Inside the main() function, initialize Flutter Stripe by setting the publishable key:

void main() async {
WidgetsFlutterBinding.ensureInitialized();
const stripePublishableKey = "YOUR_PUBLISHABLE_KEY";
Stripe.publishableKey = stripePublishableKey;
runApp(const MyApp());
}

Step 9: Define MyApp Widget In main.dart, define the MyApp widget that represents the root of your application:

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomeScreen(),
);
}
}

Step 10: Implement HomeScreen Widget In dashboard.dart, implement the HomeScreen widget as a stateful widget:

class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
_HomeScreenState createState()
=> _HomeScreenState();
}

Step 11: Implement the _HomeScreenState Class Inside _HomeScreenState, define the paymentIntent variable and implement the build method:

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: TextButton(
child: const Text('Make Payment'),
onPressed: () async {
await makePayment();
},
),
),
);
}
// Implement other methods here
}

Step 12: Implement the makePayment Method Add the makePayment method inside _HomeScreenState to handle the payment flow:

Future<void> makePayment() async {
try {
paymentIntent = await createPaymentIntent('10', 'USD');
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntent!['client_secret'],
googlePay: const PaymentSheetGooglePay(
testEnv: true,
currencyCode: "US",
merchantCountryCode: "+92"
),
style: ThemeMode.dark,
merchantDisplayName: 'Adnan',
),
);
displayPaymentSheet();
} catch (e) {
if (kDebugMode) {
print("exception $e");
}
}
}

Step 13: Implement the displayPaymentSheet Method Implement the displayPaymentSheet method to handle the presentation of the payment sheet:

displayPaymentSheet() async {
try {
await Stripe.instance.presentPaymentSheet();
showDialog(
context: context,
builder: (_) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Row(
children: [
Icon(Icons.check_circle, color: Colors.green),
Text("Payment Successful"),
],
),
],
),
),
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("Paid successfully")),
);
paymentIntent = null;
} on StripeException catch (e) {
print('Error: $e');
showDialog(
context: context,
builder: (_) => const AlertDialog(
content: Text("Cancelled"),
),
);
} catch (e) {
print('$e');
}
}

Step 14: Implement the createPaymentIntent Method Add the createPaymentIntent method to handle the creation of payment intents:

createPaymentIntent(String amount, String currency) async {
try {
Map<String, dynamic> body = {
'amount': calculateAmount(amount),
'currency': currency,
'payment_method_types[]': 'card',
};
var SECRET_KEY = "YOUR_SECRET_KEY";
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
headers: {
'Authorization': 'Bearer $SECRET_KEY',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: body,
);
print('Payment Intent Body: ${response.body.toString()}');
return jsonDecode(response.body.toString());
} catch (err) {
print('Error charging user: ${err.toString()}');
}
}

Step 15: Implement the calculateAmount Method Add the calculateAmount method to calculate the payment amount:

calculateAmount(String amount) {
final calculatedAmount = (int.parse(amount)) * 100;
return calculatedAmount.toString();
}

Make sure to replace the placeholder values, such as the publishable key and secret key, with your actual Stripe keys.

Payment Preview :

you can see all payment in payment section :

code:

main.dart

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


import 'dashboard.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
const stripePublishableKey = "YOUR_PUBLISHABLE_KEY";
Stripe.publishableKey = stripePublishableKey;
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomeScreen(),
);
}
}

dashboard.dart

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_stripe/flutter_stripe.dart';
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: TextButton(
child: const Text('Make Payment'),
onPressed: ()async{
await makePayment();
},
),
),
);
}

Future<void> makePayment() async {
try {
paymentIntent = await createPaymentIntent('10', 'USD');
//Payment Sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntent!['client_secret'],
googlePay: const PaymentSheetGooglePay(testEnv: true, currencyCode: "US", merchantCountryCode: "+92"),
style: ThemeMode.dark,
merchantDisplayName: 'Adnan')).then((value){
});


///now finally display payment sheeet
displayPaymentSheet();
}
catch (e) {
if (kDebugMode) {
print("exception $e");
}
}
}

displayPaymentSheet() async {
try {
await Stripe.instance.presentPaymentSheet(

).then((value){
showDialog(
context: context,
builder: (_) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: const [
Icon(Icons.check_circle, color: Colors.green,),
Text("Payment Successfull"),
],
),
],
),
));
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("paid successfully")));

paymentIntent = null;

}).onError((error, stackTrace){
print('Error is:--->$error $stackTrace');
});


} on StripeException catch (e) {
print('Error is:---> $e');
showDialog(
context: context,
builder: (_) => const AlertDialog(
content: Text("Cancelled "),
));
} catch (e) {
print('$e');
}
}


createPaymentIntent(String amount, String currency) async {
try {
Map<String, dynamic> body = {
'amount': calculateAmount(amount),
'currency': currency,
'payment_method_types[]': 'card',
};
var SECRET_KEY = "YOUR_SECRET_KEY";
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
headers: {
'Authorization': 'Bearer $SECRET_KEY',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: body,
);
// ignore: avoid_print
print('Payment Intent Body->>> ${response.body.toString()}');
return jsonDecode(response.body.toString());
} catch (err) {
// ignore: avoid_print
print('err charging user: ${err.toString()}');
}
}


calculateAmount(String amount) {
final calculatedAmout = (int.parse(amount)) * 100 ;
return calculatedAmout.toString();
}

}

Implementation :


follow my Instagram account :

https://www.instagram.com/nature.pulse_/

Conclusion :

By implementing Stripe into your Flutter app, you can provide a secure and seamless payment experience to your users. Enjoy the convenience of integrating a trusted payment platform and enhance your app’s capabilities. Embrace this opportunity to level up your skills and deliver an exceptional user experience.


Post a Comment

0 Comments