While Initializing payment sheet in flutter for stripe I get null as return value

205 Views Asked by At

I am trying to integrate Flutter with Stripe.

The following code is how I create payment intent

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

  const String secretKey =
      'Stripe_Secret_Key';

  final response = await http.post(
    Uri.parse('https://api.stripe.com/v1/payment_intents'),
    headers: {
      'Authorization': 'Bearer $secretKey',
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: body,
  );

  if (response.statusCode == 200) {
    final Map<String, dynamic> responseData = json.decode(response.body);
    return responseData;
  } else {
    throw Exception('Failed to create payment intent');
  }
}

To make a payment request I am calling the following function which is calling the above function to get the client_secret

Future<void> makePayment() async {
    try {
      paymentIntent = await createPaymentIntent('10', 'USD');
      if (paymentIntent == null) {
        return;
      }

      logger.d(paymentIntent!['client_secret']);

      // STEP 2: Initialize payment sheet
      final result = await Stripe.instance.initPaymentSheet(
        paymentSheetParameters: SetupPaymentSheetParameters(
          paymentIntentClientSecret:
              paymentIntent!['client_secret'], // from payment intent
          style: ThemeMode.light,
          merchantDisplayName: 'Test Dev',
        ),
      );

      logger.d(result); // This line prints null in console

      // STEP 3: Display payment sheet
      displayPaymentSheet();
    } catch (e) {
      //    Handle any other unexpected errors.
      debugPrint('Error: $e');
    }
  }

The following code is for displaying the payment sheet.

displayPaymentSheet() async {
    final paymentResult = await Stripe.instance.presentPaymentSheet();
    logger.d(paymentResult);
  }

Since the payment was constantly failing, I carefully reviewed each step to identify where the error was occurring. I verified that I was receiving paymentIntent!['client_secret'] from the paymentIntent, and that was working correctly. However, when I checked for Stripe.instance.initPaymentSheet(), it returned a null value. I have followed the official documentation from GitHub, but nothing seems to work. The payment sheet appears on the screen but it fails on clicking the send button. How can I resolve this issue?

I followed the official documentation from GitHub. I also verified my code from medium articles and a few YouTube videos. But nothing seems to work.

0

There are 0 best solutions below