runWebPaymentRequest function

Future<void> runWebPaymentRequest(
  1. BuildContext context, {
  2. required String publishableKey,
  3. String? clientSecret,
  4. required String method,
  5. required String amount,
  6. Map<String, dynamic>? merchantArgs,
  7. void onResult(
    1. StripePaymentResult
    )?,
})

Helper for web to run a payment flow. NOTE: showLpePaysheet uses webview_flutter (which requires a platform implementation). On web browsers we cannot construct that WebView controller, so prefer a native web flow. If a full PaymentRequest implementation is not available, we return a friendly failure instead of crashing.

Implementation

Future<void> runWebPaymentRequest(
  BuildContext context, {
  required String publishableKey,
  String? clientSecret,
  required String method,
  required String amount,
  Map<String, dynamic>? merchantArgs,
  void Function(StripePaymentResult)? onResult,
}) async {
  if (!kIsWeb) {
    await showLpePaysheet(
      context,
      publishableKey: publishableKey,
      clientSecret: clientSecret,
      method: method,
      amount: amount,
      merchantArgs: merchantArgs,
      mountOnShow: true,
      enableStripeJs: true,
      onResult: onResult,
    );
    return;
  }

  // Running on web: attempt PaymentRequest if available (Chrome/Edge),
  // otherwise fall back to a friendly error. We deliberately avoid
  // instantiating WebViewController to prevent the platform assertion.
  try {
    final hasPR = js_util.hasProperty(html.window, 'PaymentRequest') ||
        (js_util.hasProperty(html.window, 'google') &&
            js_util.hasProperty(
                js_util.getProperty(html.window, 'google'), 'payments'));
    if (hasPR) {
      // Minimal informative flow: notify caller to implement PaymentRequest
      // integration if they need a full web Google Pay flow. Return a
      // structured error so UI shows a friendly message.
      const res = StripePaymentResult(
        success: false,
        error: 'payment_request_not_implemented',
        errorMessage:
            'PaymentRequest flow is available in this browser but not implemented by the SDK. Please integrate PaymentRequest for full Google Pay on web.',
      );
      onResult?.call(res);
      return;
    }
  } catch (_) {}

  // Generic web fallback: show a dialog and return an error result.
  showDialog<void>(
    context: context,
    builder: (ctx) => AlertDialog(
      title: const Text('Web Payment Unavailable'),
      content: const Text(
          'This browser does not support the built-in web payment flow. Please try Chrome or use the native app.'),
      actions: [
        TextButton(
            onPressed: () => Navigator.of(ctx).pop(), child: const Text('OK'))
      ],
    ),
  );

  const fallback = StripePaymentResult(
    success: false,
    error: 'web_payment_unavailable',
    errorMessage:
        'Web payment is unavailable in this browser. Try Chrome or the native app.',
  );
  onResult?.call(fallback);
}