flutterdartgoogle-payflutter-inappwebviewpub.dev

Gpay button is not displaying in the Flutter


I am trying to display payment button in the Inappwebview, but the button is not showing in flutter

I am using the dependency for the web view

flutter_inappwebview: ^6.1.5

and I ma using the code

    Padding(
                        padding: EdgeInsets.only(
                            bottom: MediaQuery.of(context).padding.bottom),
                        child: InAppWebView(
                          initialUrlRequest: URLRequest(
                            url: WebUri(widget.urlRequest!),
                          ),
                          initialData: widget.pageType?.toUpperCase() != 'INBOX'
                              ? InAppWebViewInitialData(data: widget.htmlData!)
                              : null,
                          onConsoleMessage: (controller, consoleMessage) {
                            debugPrint("JS Console: ${consoleMessage.message}");
                          },
                          initialOptions: InAppWebViewGroupOptions(
                              android: AndroidInAppWebViewOptions(
                                clearSessionCache: true,
                                useHybridComposition: true,
                                disableDefaultErrorPage: false,
                              ),
                              ios: IOSInAppWebViewOptions(
                                  allowsInlineMediaPlayback: true),
                              crossPlatform: InAppWebViewOptions(
                                  useOnLoadResource: true,
                                  mediaPlaybackRequiresUserGesture: false,
                                  useShouldOverrideUrlLoading: true,
                                  transparentBackground: true,
                                  javaScriptEnabled: true)),
                          onWebViewCreated: (controller) {
                            webViewController = controller;
                          },
                          onLoadStart: (controller, url) {
                            handleLoadStart();
                          },
                          onLoadStop: (controller, url) async {
                            await handleLoadStop();
                            webViewController?.evaluateJavascript(
                                source:
                                    "Update_Info('${widget.updateInfoString}')");
                          },
                          onLoadError: (controller, url, code, message) async {
                            await handleLoadError();
                          },
                          onLoadHttpError:
                              (controller, url, statusCode, description) async {
                            await handleLoadHttpError();
                          },
                          shouldOverrideUrlLoading:
                              (webViewController, navigationAction) async {
                            final uri = navigationAction.request.url!;
                            if (kDebugMode) {
                              debugPrint("data here-->$uri");
                            }

                            webViewController.evaluateJavascript(
                                source:
                                    "Update_Info('${widget.updateInfoString}')");
 if (uri.scheme == 'buttontap' &&
                                uri.host.toLowerCase() == 'actionbutton' &&
                                uri.path
                                    .toLowerCase()
                                    .contains('/paywithpoints')) {
                              final isLogin = await Common.userInfoTable
                                  .getLoggedInStatus();
                              final isRegister =
                                  await Common.userInfoTable.isRegistered();
                              if (isRegister) {
                                if (isLogin == "1") {
                                  if (await RXCommon.isInternetConnected()) {
                                    _isPaymentProcessed = false;
                                  }

                                  if (_isPaymentProcessed) {
                                    return NavigationActionPolicy.CANCEL;
                                  }

                                  try {
                                    _isPaymentProcessed = true;

                                    // ✅ Inject Update_Info JS function before starting payment logic
                                    await webViewController.evaluateJavascript(
                                        source:
                                            "Update_Info('${widget.updateInfoString}')");

                                    String? data =
                                        uri.queryParameters['Data'] ?? "";
                                    debugPrint("DATAFORGOOGLEPAY======>$data");

                                    String absoluteUrl = uri.toString();
                                    String payData = '';

                                    if (absoluteUrl.isNotEmpty &&
                                        data.isNotEmpty) {
                                      payData = Common.decodeBase64String(data);
                                    }

                                    String compSummary = '';
                                    String compSummaryData = '';

                                    if (payData.isNotEmpty) {
                                      compType =
                                          RXP2AppSpecific.getQueryStringValue(
                                              payData, "compType");
                                      compSummary =
                                          RXP2AppSpecific.getQueryStringValue1(
                                              payData, "compSummary");
                                      compTotalAmount =
                                          RXP2AppSpecific.getQueryStringValue(
                                              payData, "totalAmt");

                                      if (compSummary.isNotEmpty) {
                                        compSummaryData =
                                            Common.decodeBase64String(
                                                compSummary);
                                      }
                                    }

                                    if (compTotalAmount.isNotEmpty &&
                                        compSummary.isNotEmpty) {
                                      Map<String, dynamic> resData =
                                          jsonDecode(compSummaryData);
                                      List<dynamic> compSummaryDataList =
                                          resData['CompSummary'];
                                      _paymentItems.clear();

                                      if (compSummaryDataList.isNotEmpty) {
                                        for (int i = 0;
                                            i < compSummaryDataList.length;
                                            i++) {
                                          Map<String, dynamic> dict =
                                              compSummaryDataList[i];

                                          String summaryItemName = dict['Name'];
                                          String summaryItemAmount =
                                              dict['Amt'];

                                          double summaryAmount =
                                              double.parse(summaryItemAmount);

                                          _paymentItems.add(PaymentItem(
                                            label: summaryItemName,
                                            amount: summaryAmount.toString(),
                                            status:
                                                PaymentItemStatus.final_price,
                                          ));
                                        }
                                      }

                                      _paymentItems.add(PaymentItem(
                                        label: compType,
                                        amount: compTotalAmount,
                                        status: PaymentItemStatus.final_price,
                                      ));
                                    }

                                    if (Platform.isIOS) {
                                      final result =
                                          await _payClient.showPaymentSelector(
                                              PayProvider.apple_pay,
                                              _paymentItems);
                                      onApplePayResult(result);

                                      String token = result['token'];
                                      Map<String, dynamic> paymentMethod =
                                          result['paymentMethod'];
                                      String transactionIdentifier =
                                          result['transactionIdentifier'];

                                      Map<String, dynamic> requestItemData = {
                                        "paymentData": token.toString(),
                                        "paymentMethod":
                                            paymentMethod.toString(),
                                        "transactionIdentifier":
                                            transactionIdentifier.toString()
                                      };

                                      String paymentrequestItemData =
                                          jsonEncode(requestItemData);
                                      String base64Token =
                                          Common.encodeBase64String(
                                              paymentrequestItemData);

                                      await webViewController.evaluateJavascript(
                                          source:
                                              "ApplePaymentJS('$base64Token')");

                                      debugPrint(
                                          "ApplePay Token Data: $base64Token");
                                      debugPrint('ApplePay Result: $result');
                                    } else if (Platform.isAndroid) {
                                      final result =
                                          await _payClient.showPaymentSelector(
                                              PayProvider.google_pay,
                                              _paymentItems);
                                      onGooglePayResult(result);

                                      Map<String, dynamic> paymentMethodData =
                                          result['paymentMethodData'];
                                      Map<String, dynamic> tokenizationData =
                                          paymentMethodData['tokenizationData'];
                                      String token = tokenizationData['token'];
                                      String base64Token =
                                          Common.encodeBase64String(token);

                                      await webViewController.evaluateJavascript(
                                          source:
                                              "GooglePaymentJS('$base64Token')");

                                      debugPrint(
                                          "GooglePay Token Data: $base64Token");
                                      debugPrint('GooglePay Result: $result');
                                    }
                                  } catch (error) {
                                    _isPaymentProcessed = false;
                                    if (kDebugMode) {
                                      debugPrint(
                                          "RXPAYERROR: ${error.toString()}");
                                    }
                                  }

                                  return NavigationActionPolicy.ALLOW;
                                } else {
                                  userLogin(context);
                                  return NavigationActionPolicy.CANCEL;
                                }
                              } else {
                                redirectToRegisterPage(context);
                              }
                            }

Give me solution for this, but its working in the Native android

This is the output I am expecting, which is taken from the Native Android

enter image description here

I am getting like this in Flutter

enter image description here


Solution

  • Google Pay requires the page to run in a secure context (https:). When you load HTML as a string via InAppWebViewInitialData, it defaults to null or about:blanknot secure, so GPay JS fails silently.

    baseUrl: WebUri("https://dummy.page")
    

    makes the WebView behave as if the page is loaded from HTTPS, and the GPay script (pay.js) will proceed to render the button inside your HTML popup.

    Try this:

    initialData: widget.pageType?.toUpperCase() != 'INBOX'
        ? InAppWebViewInitialData(
            data: widget.htmlData!,
            baseUrl: WebUri("https://dummy.page"), // ✅ This is critical
          )
        : null,