Muhammad Luqman
ย ยทย FlutterFlow Expert | Flutter | OpenAI | Software Engineer

Implementing Google Pay and Apple Pay with Stripe

Google Pay:

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/actions/actions.dart' as action_blocks;
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:flutter_stripe/flutter_stripe.dart';

Future<dynamic?> payWithGoogle(
  BuildContext context,
  String clientSecret,
) async {
  final googlePaySupported = await Stripe.instance
      .isPlatformPaySupported(googlePay: IsGooglePaySupportedParams());

  if (googlePaySupported) {
    try {
      final paymentMethod =
          await Stripe.instance.confirmPlatformPayPaymentIntent(
        clientSecret: clientSecret,
        confirmParams: const PlatformPayConfirmParams.googlePay(
          googlePay: GooglePayParams(
            testEnv: true,
            merchantName: 'Masjid Hero',
            merchantCountryCode: 'US',
            currencyCode: 'USD',
          ),
        ),
      );

      final paymentIntentJson = {
        'id': paymentMethod.id,
        'amount': paymentMethod.amount,
        'created': paymentMethod.created,
        'currency': paymentMethod.currency,
        'status': paymentMethod.status.name, // Convert enum to string
        'clientSecret': paymentMethod.clientSecret,
        'livemode': paymentMethod.livemode,
        'captureMethod': paymentMethod.captureMethod.name,
        'confirmationMethod': paymentMethod.confirmationMethod.name,
        'paymentMethodId': paymentMethod.paymentMethodId,
        'description': paymentMethod.description,
        'receiptEmail': paymentMethod.receiptEmail,
        'canceledAt': paymentMethod.canceledAt,
        'nextAction': paymentMethod.nextAction,
        'shipping': paymentMethod.shipping,
        'mandateData': paymentMethod.mandateData,
        'latestCharge': paymentMethod.latestCharge,
      };

      return paymentIntentJson;
    } catch (e) {
      if (e is StripeException) {
        final errorMessage = e.error.localizedMessage ??
            "An unknown error occurred.Please try again.";
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              errorMessage,
              style: TextStyle(
                color: FlutterFlowTheme.of(context).info,
              ),
            ),
            duration: const Duration(milliseconds: 4000),
            backgroundColor: FlutterFlowTheme.of(context).error,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'Payment was cancelled by the user.',
              style: TextStyle(
                color: FlutterFlowTheme.of(context).info,
              ),
            ),
            duration: const Duration(milliseconds: 4000),
            backgroundColor: FlutterFlowTheme.of(context).error,
          ),
        );
      }
      return null;
    }
  } else {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          'Google Pay is not supported on this device.',
          style: TextStyle(
            color: FlutterFlowTheme.of(context).info,
          ),
        ),
        duration: const Duration(milliseconds: 4000),
        backgroundColor: FlutterFlowTheme.of(context).error,
      ),
    );
    return null;
  }
}

// Set your action name, define your arguments and return parameter,
// and then add the boilerplate code using the green button on the right!

Apple Pay:

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/actions/actions.dart' as action_blocks;
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:flutter_stripe/flutter_stripe.dart';

Future<dynamic?> payWithApple(
    BuildContext context, String clientSecret, double amount) async {
  final applePaySupported = await Stripe.instance.isPlatformPaySupported();
  if (applePaySupported) {
    try {
      final paymentMethod =
          await Stripe.instance.confirmPlatformPayPaymentIntent(
        clientSecret: clientSecret,
        confirmParams: PlatformPayConfirmParams.applePay(
          applePay: ApplePayParams(
            merchantCountryCode: 'US',
            currencyCode: 'usd',
            cartItems: [
              ApplePayCartSummaryItem.immediate(
                label: "Total Payable Amount",
                amount: amount.toString(),
              ),
            ],
          ),
        ),
      );

      final paymentIntentJson = {
        'id': paymentMethod.id,
        'amount': paymentMethod.amount,
        'created': paymentMethod.created,
        'currency': paymentMethod.currency,
        'status': paymentMethod.status.name, // Convert enum to string
        'clientSecret': paymentMethod.clientSecret,
        'livemode': paymentMethod.livemode,
        'captureMethod': paymentMethod.captureMethod.name,
        'confirmationMethod': paymentMethod.confirmationMethod.name,
        'paymentMethodId': paymentMethod.paymentMethodId,
        'description': paymentMethod.description,
        'receiptEmail': paymentMethod.receiptEmail,
        'canceledAt': paymentMethod.canceledAt,
        'nextAction': paymentMethod.nextAction,
        'shipping': paymentMethod.shipping,
        'mandateData': paymentMethod.mandateData,
        'latestCharge': paymentMethod.latestCharge,
      };

      return paymentIntentJson;
    } catch (e) {
      if (e is StripeException) {
        final errorMessage = e.error.localizedMessage ??
            "An unknown error occurred.Please try again.";
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              errorMessage,
              style: TextStyle(
                color: FlutterFlowTheme.of(context).info,
              ),
            ),
            duration: const Duration(milliseconds: 4000),
            backgroundColor: FlutterFlowTheme.of(context).error,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'Payment was cancelled by the user.',
              style: TextStyle(
                color: FlutterFlowTheme.of(context).info,
              ),
            ),
            duration: const Duration(milliseconds: 4000),
            backgroundColor: FlutterFlowTheme.of(context).error,
          ),
        );
      }
      return null;
    }
  } else {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          'Apple Pay is not supported on this device.',
          style: TextStyle(
            color: FlutterFlowTheme.of(context).info,
          ),
        ),
        duration: const Duration(milliseconds: 4000),
        backgroundColor: FlutterFlowTheme.of(context).error,
      ),
    );
    return null;
  }
}

// Set your action name, define your arguments and return parameter,
// and then add the boilerplate code using the green button on the right!

โœ… Stripe Integration with Google Pay and Apple Pay

๐Ÿ“Œ Overview

If you're integrating Stripe with APIs and want to support Google Pay and Apple Pay, you need to implement custom code to display the payment options. The process is straightforward: create a Payment Intent using the Stripe AP for the specified amount and follow the outlined methods to ensure smooth payment handling.

โš™๏ธ Implementation Details

  • โœ… Apple Pay: You need to pass the total amount along with the client_secret ID of the Stripe Payment Intent.

  • โœ… Google Pay: You only need to pass the client_secret ID of the Stripe Payment Intent. For the live environment, please make testEnv should be false.

 testEnv: true,

โ— Error Handling

This implementation includes robust error handling to manage scenarios where:

  • โŒ The payment fails.

  • ๐Ÿšซ Google Pay or Apple Pay is not supported on the user's device.

๐Ÿ“„ Response Handling

Upon successful payment, the system returns a JSON response containing:

  • โœ… Payment ID

  • โœ… Additional transaction details relevant to the user

๐Ÿ“ฆ Required Package

  • Ensure you have the flutter_stripe package installed in your Flutterflow project to handle Stripe payments effectively.

๐ŸŽฏ Conclusion

This integration ensures a seamless payment experience using Google Pay and Apple Pay with Stripe. If you found any issue, please don't hesitate to reach me out.

If you found this documentation helpful, please โœ… like, ๐Ÿ”„ share, and ๐Ÿ’ฌ comment!

10