Sitemap

Exploring the Stripe Payment Gateway In Flutter

7 min readJul 27, 2022

Stripe payment gateway integration in flutter project.

Stripe is a popular payment processor that makes it easy for developers to integrate payment methods into mobile applications. With a heavy focus on UX and security, Stripe has shaken up the e-commerce industry with its popularity among both shoppers and developers.

Let’s take a look at some of Stripe’s features that we’ll integrate into our Flutter app using the Stripe Flutter SDK.

Table of Content :

Introduction

Features

Stripe account and Generate the API keys

Stripe SDK Setup/Configuration in flutter project

Implementation

Conclusion

1. Introduction

The Stripe Flutter SDK allows you to build delightful payment experiences in your native Android and iOS apps using Flutter. We provide powerful and customizable UI screens and elements that can be used out-of-the-box to collect your users’ payment details.

2. Features

Simplified Security: We make it simple for you to collect sensitive data such as credit card numbers and remain PCI compliant. This means the sensitive data is sent directly to Stripe instead of passing through your server. For more information, see our Integration Security Guide.

Apple Pay: We provide a seamless integration with Apple Pay.

Google Pay: The plugin can easily act as payment provider for the Pay plugin that enables you to seamlessly integrate Google Pay or Apple Pay. All you need to do is add your stripe publishable key to the payment profile.

Payment methods: Accepting more payment methods helps your business expand its global reach and improve checkout conversion.

SCA-Ready: The SDK automatically performs native 3D Secure authentication if needed to comply with Strong Customer Authentication regulation in Europe.

Native UI: We provide native screens and elements to securely collect payment details on Android and iOS.

Pre-built payments UI: Learn how to integrate Payment Sheet, the new pre-built payments UI for mobile apps. This pre-built UI lets you accept cards, Apple Pay, and Google Pay out of the box, and includes support for saving & reusing cards.

If you’re selling digital products or services within your app, (e.g. subscriptions, in-game currencies, game levels, access to premium content, or unlocking a full version), you must use the app store’s in-app purchase APIs. See Apple’s and Google’s guidelines for more information. For all other scenarios you can use this SDK to process payments via Stripe.

3. Stripe account and Generate the API keys

  1. Sign in to your Dashboard with suitable credentials.
  2. Select the mode (Test or Live) for which you need to create the API key. Stripe API Key Docs
  3. Explore to DashboardAPI KeysGenerate Key to generate the key for either test or live environment.
  4. You can test all the possible test cases of the payment in test environment. You can enable Test environment by clicking the test mode switch from top right corner in the Dashboard.

Note: You need to generate the separate API Keys for the test and live modes.

4. Stripe SDK Setup/Configuration in flutter project

Step 1: Add the dependencies

by Running this command With Flutter:

flutter pub add flutter_stripe

or you can manually add the dependency in pubspec.yaml (and run an implicit flutter pub get)

dependencies:
flutter_stripe: ^4.0.0

Step 2: Import

Now in your Dart code, you can use:

import 'package:flutter_stripe/flutter_stripe.dart';

Step 3: Requirements

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.5.0 and above.
  3. Using a descendant of Theme.AppCompat for your activity: example, example night theme
  4. Using an up-to-date Android gradle build tools version and an up-to-date gradle version accordingly
  5. Using FlutterFragmentActivity instead of FlutterActivity in MainActivity.kt: example
  6. 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 their UI components and the Support Fragment Manager for the Payment Sheets.

iOS

Compatible with apps targeting iOS 12 or above.

4. Implementation

  1. Initialize the flutter SDK settings to your main.dart file.
// main.dart
import 'package:flutter_stripe/flutter_stripe.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

// set the publishable key for Stripe - this is mandatory
Stripe.publishableKey = stripePublishableKey; Stripe.merchantIdentifier = 'merchant.flutter.stripe.test'; Stripe.urlScheme = 'flutterstripe';
await Stripe.instance.applySettings();
}

2. Make API at the server side:

This integration requires endpoints on your server that talk to the Stripe API. Use our official libraries for access to the Stripe API from your server. This API call will return 3 params in response which is used to initiate the payment sheet at client side.

ClientSecretKey

EphemeralKey

CustomerId

Note: You can refer official docs of the Stripe for more detail about this : Link

Server -Side Code method:

// customerId is the Identifier of the client, who is making Paymentpublic PaymentIntentDTO getPaymentIntentData(String customerId, String amount) throws StripeException {

Stripe.apiKey = stripeApiKey;

// get client secret
List<Object> paymentMethodTypes = new ArrayList<>();
paymentMethodTypes.add("card");
Map<String, Object> params = new HashMap<>();
params.put("customer", customerId);
params.put("amount", amount);
params.put("currency", "usd");

Map<String,Boolean> automaticPaymentMethodsMap = new HashMap<>();
automaticPaymentMethodsMap.put("enabled", true);
params.put("automatic_payment_methods", automaticPaymentMethodsMap);

PaymentIntent paymentIntent = PaymentIntent.create(params);

// get ephemeral key
EphemeralKeyCreateParams empEphemeralKeyCreateParams = EphemeralKeyCreateParams.builder().setCustomer(customerId).build();
RequestOptions requestOptions = RequestOptions.builder().setStripeVersionOverride(Stripe.API_VERSION).build();
EphemeralKey ephemeralKey = EphemeralKey.create(empEphemeralKeyCreateParams, requestOptions);

PaymentIntentDTO paymentIntentDTO = new PaymentIntentDTO();
paymentIntentDTO.setClientSecret(paymentIntent.getClientSecret());
paymentIntentDTO.setEphemeralKey(ephemeralKey.getId());
paymentIntentDTO.setCustomerId(customerId);

return paymentIntentDTO;
}


// Response DTO.
public class PaymentIntentDTO {

/** The client secret. */
private String clientSecret;

/** The ephemeral key. */
private String ephemeralKey;

/** The customer id. */
private String customerId;
}

At the client-side, Create the payment-sheet.

Future<Map<String, dynamic>> _createTestPaymentSheet() async {
final url = Uri.parse('$kApiUrl/payment-sheet');
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
},
body: json.encode({
'a': 'a',
}),
);
final body = json.decode(response.body);
if (body['error'] != null) {
throw Exception(body['error']);
}
return body;
}

Future<void> initPaymentSheet() async {
try {
// 1. create payment intent on the server
final data = await _createTestPaymentSheet();

// create some billingdetails
final billingDetails = BillingDetails(
name: 'Flutter Stripe',
email: 'email@stripe.com',
phone: '+48888000888',
address: Address(
city: 'Houston',
country: 'US',
line1: '1459 Circle Drive',
line2: '',
state: 'Texas',
postalCode: '77063',
),
); // mocked data for tests

// 2. initialize the payment sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
// Main params
paymentIntentClientSecret: data['paymentIntent'],
merchantDisplayName: 'Flutter Stripe Store Demo',
// Customer params
customerId: data['customer'],
customerEphemeralKeySecret: data['ephemeralKey'],
// Extra params
applePay: PaymentSheetApplePay(
merchantCountryCode: 'DE',
),
googlePay: PaymentSheetGooglePay(
merchantCountryCode: 'DE',
testEnv: true,
),
style: ThemeMode.dark,
appearance: PaymentSheetAppearance(
colors: PaymentSheetAppearanceColors(
background: Colors.lightBlue,
primary: Colors.blue,
componentBorder: Colors.red,
),
shapes: PaymentSheetShape(
borderWidth: 4,
shadow: PaymentSheetShadowParams(color: Colors.red),
),
primaryButton: PaymentSheetPrimaryButtonAppearance(
shapes: PaymentSheetPrimaryButtonShape(blurRadius: 8),
colors: PaymentSheetPrimaryButtonTheme(
light: PaymentSheetPrimaryButtonThemeColors(
background: Color.fromARGB(255, 231, 235, 30),
text: Color.fromARGB(255, 235, 92, 30),
border: Color.fromARGB(255, 235, 92, 30),
),
),
),
),
billingDetails: billingDetails,
),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error: $e')),
);
rethrow;
}
}

Call the below method to present the payment sheet to the user.

Future<void> confirmPayment() async {
try {
// InIt the payment sheet.
await initPaymentSheet();
// Display the payment sheet.
await Stripe.instance.presentPaymentSheet();

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Payment succesfully completed'),
),
);
} on Exception catch (e) {
if (e is StripeException) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error from Stripe: ${e.error.localizedMessage}'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Unforeseen error: ${e}'),
),
);
}
}
}
Android Screenshot
iOS Screenshot

More About Flutter Stripe SDK:

Dart API

The library offers several methods to handle stripe related actions:

Future<PaymentMethod> createPaymentMethod(...);
Future<PaymentIntent> handleNextAction(...);
Future<PaymentIntent> confirmPayment(...);
Future<void> configure3dSecure(...);
Future<bool> isApplePaySupported();
Future<void> presentApplePay(...);
Future<void> confirmApplePayPayment(...);
Future<SetupIntent> confirmSetupIntent(...);
Future<PaymentIntent> retrievePaymentIntent(...);
Future<String> createTokenForCVCUpdate(...);
Future<void> initPaymentSheet(...);
Future<void> presentPaymentSheet(...);
Future<void> confirmPaymentSheetPayment()

Pay Plugin support

flutter_stripe fully supports the Pay plugin from the Google Pay team. By including a few lines you can integrate Stripe as a payment processor for Google / Apple Pay:

Future<void> onGooglePayResult(paymentResult) async {
final response = await fetchPaymentIntentClientSecret();
final clientSecret = response['clientSecret'];
final token = paymentResult['paymentMethodData']['tokenizationData']['token'];
final tokenJson = Map.castFrom(json.decode(token));
final params = PaymentMethodParams.cardFromToken(
token: tokenJson['id'],
);
// Confirm Google pay payment method
await Stripe.instance.confirmPayment(
clientSecret,
params,
);
}

Conclusion:

I hope this blog will provide you with sufficient information in Trying up Stripe Payment in Flutter in your flutter projects. This is a demo example that will integrate Stripe payment in a flutter. We will describe all basic points, and you will use in your flutter application for payment purpose, So please try it.

❤ ❤ Thanks for reading this article ❤ ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

find the source code of the Flutter Stripe Payment Demo:

GitHub — flutter-stripe/flutter_stripe: Flutter SDK for Stripe.

--

--

Alfaizkhan Pathan
Alfaizkhan Pathan

Written by Alfaizkhan Pathan

Android & Flutter Developer📱 | Flutter Enthusiast💙

No responses yet