googlePay static method

Future<void> googlePay({
  1. required PaymentRequest paymentRequest,
  2. required void onGooglePayResult(
    1. Map<String, dynamic> onApplePayResult
    ),
  3. void onGooglePayError(
    1. Object error
    )?,
})

Implementation

static Future<void> googlePay({
  required PaymentRequest paymentRequest,
  required void Function(Map<String, dynamic> onGooglePayResult) onGooglePayResult,
  void Function(Object error)? onGooglePayError,
}) async {
  if (!Platform.isAndroid) {
    final error = UnsupportedError('Google Pay is only supported on Android.');
    if (onGooglePayError != null) {
      onGooglePayError(error);
      return;
    }
    throw error;
  }

  final json = await _googlePayJsonFromSdk(paymentRequest);
  if (json == null || json.trim().isEmpty) {
    final error = StateError(
      'Google Pay configuration is unavailable for this payment request.',
    );
    if (onGooglePayError != null) {
      onGooglePayError(error);
      return;
    }
    throw error;
  }

  final config = PaymentConfiguration.fromJsonString(json);
  final items = paymentItemsFromRequest(paymentRequest);
  final payClient = Pay({PayProvider.google_pay: config});

  try {
    final result = await payClient.showPaymentSelector(
      PayProvider.google_pay,
      items,
    );
    onGooglePayResult(Map<String, dynamic>.from(result));
  } catch (error) {
    if (onGooglePayError != null) {
      final errorStr = error.toString().toLowerCase();
      if (errorStr.contains('canceled') || errorStr.contains('cancelled')) {
        onGooglePayError('Transaction cancelled by user');
      } else {
        onGooglePayError(error);
      }
    } else {
      rethrow;
    }
  }
}